From 1ca3e1b5db66253f1b68e8172e9b6575ef66fed2 Mon Sep 17 00:00:00 2001 From: KiCAD MCP Bot Date: Wed, 5 Nov 2025 21:27:41 -0500 Subject: [PATCH] feat: Add JSON-RPC 2.0 MCP protocol support for Claude Desktop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit fixes Windows Claude Desktop compatibility by implementing proper MCP JSON-RPC 2.0 protocol handling in the Python interface. Changes: - Added JSON-RPC 2.0 message detection and handling - Implemented MCP protocol methods: initialize, tools/list, tools/call - Maintained backwards compatibility with legacy custom format - Removed accidentally included typescript-sdk directory Fixes #5 - Claude Desktop not working on Windows Credit to @spplecxer for identifying the issue and providing the fix. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- python/kicad_interface.py | 112 +- typescript-sdk/.git-blame-ignore-revs | 0 typescript-sdk/.gitattributes | 1 - typescript-sdk/.github/CODEOWNERS | 11 - typescript-sdk/.github/workflows/main.yml | 51 - typescript-sdk/.gitignore | 135 - typescript-sdk/.npmrc | 1 - typescript-sdk/.prettierignore | 10 - typescript-sdk/.prettierrc.json | 20 - typescript-sdk/CLAUDE.md | 28 - typescript-sdk/CODE_OF_CONDUCT.md | 83 - typescript-sdk/CONTRIBUTING.md | 50 - typescript-sdk/LICENSE | 21 - typescript-sdk/README.md | 1511 ---- typescript-sdk/SECURITY.md | 15 - typescript-sdk/eslint.config.mjs | 26 - typescript-sdk/jest.config.js | 14 - typescript-sdk/package-lock.json | 6812 ----------------- typescript-sdk/package.json | 128 - .../src/__mocks__/pkce-challenge.ts | 6 - typescript-sdk/src/cli.ts | 161 - typescript-sdk/src/client/auth.test.ts | 2446 ------ typescript-sdk/src/client/auth.ts | 1053 --- typescript-sdk/src/client/cross-spawn.test.ts | 152 - typescript-sdk/src/client/index.test.ts | 1241 --- typescript-sdk/src/client/index.ts | 440 -- typescript-sdk/src/client/middleware.test.ts | 1105 --- typescript-sdk/src/client/middleware.ts | 319 - typescript-sdk/src/client/sse.test.ts | 1484 ---- typescript-sdk/src/client/sse.ts | 275 - typescript-sdk/src/client/stdio.test.ts | 77 - typescript-sdk/src/client/stdio.ts | 236 - .../src/client/streamableHttp.test.ts | 1076 --- typescript-sdk/src/client/streamableHttp.ts | 560 -- typescript-sdk/src/client/websocket.ts | 74 - typescript-sdk/src/examples/README.md | 304 - .../client/multipleClientsParallel.ts | 154 - .../client/parallelToolCallsClient.ts | 196 - .../src/examples/client/simpleOAuthClient.ts | 420 - .../examples/client/simpleStreamableHttp.ts | 837 -- .../streamableHttpWithSseFallbackClient.ts | 191 - .../server/demoInMemoryOAuthProvider.test.ts | 285 - .../server/demoInMemoryOAuthProvider.ts | 232 - .../src/examples/server/elicitationExample.ts | 476 -- .../server/jsonResponseStreamableHttp.ts | 186 - .../examples/server/mcpServerOutputSchema.ts | 80 - .../src/examples/server/simpleSseServer.ts | 174 - .../server/simpleStatelessStreamableHttp.ts | 180 - .../examples/server/simpleStreamableHttp.ts | 698 -- .../sseAndStreamableHttpCompatibleServer.ts | 260 - .../standaloneSseWithGetStreamableHttp.ts | 127 - .../examples/server/toolWithSampleServer.ts | 56 - .../src/examples/shared/inMemoryEventStore.ts | 78 - typescript-sdk/src/inMemory.test.ts | 119 - typescript-sdk/src/inMemory.ts | 63 - .../integration-tests/process-cleanup.test.ts | 28 - .../stateManagementStreamableHttp.test.ts | 357 - .../taskResumability.test.ts | 270 - typescript-sdk/src/server/auth/clients.ts | 22 - typescript-sdk/src/server/auth/errors.ts | 203 - .../server/auth/handlers/authorize.test.ts | 326 - .../src/server/auth/handlers/authorize.ts | 173 - .../src/server/auth/handlers/metadata.test.ts | 78 - .../src/server/auth/handlers/metadata.ts | 19 - .../src/server/auth/handlers/register.test.ts | 271 - .../src/server/auth/handlers/register.ts | 119 - .../src/server/auth/handlers/revoke.test.ts | 229 - .../src/server/auth/handlers/revoke.ts | 79 - .../src/server/auth/handlers/token.test.ts | 478 -- .../src/server/auth/handlers/token.ts | 157 - .../auth/middleware/allowedMethods.test.ts | 75 - .../server/auth/middleware/allowedMethods.ts | 20 - .../server/auth/middleware/bearerAuth.test.ts | 438 -- .../src/server/auth/middleware/bearerAuth.ts | 96 - .../server/auth/middleware/clientAuth.test.ts | 132 - .../src/server/auth/middleware/clientAuth.ts | 72 - typescript-sdk/src/server/auth/provider.ts | 83 - .../auth/providers/proxyProvider.test.ts | 343 - .../server/auth/providers/proxyProvider.ts | 234 - typescript-sdk/src/server/auth/router.test.ts | 463 -- typescript-sdk/src/server/auth/router.ts | 232 - typescript-sdk/src/server/auth/types.ts | 36 - typescript-sdk/src/server/completable.test.ts | 46 - typescript-sdk/src/server/completable.ts | 79 - typescript-sdk/src/server/elicitation.test.ts | 642 -- typescript-sdk/src/server/index.test.ts | 955 --- typescript-sdk/src/server/index.ts | 390 - typescript-sdk/src/server/mcp.test.ts | 4122 ---------- typescript-sdk/src/server/mcp.ts | 1197 --- typescript-sdk/src/server/sse.test.ts | 710 -- typescript-sdk/src/server/sse.ts | 213 - typescript-sdk/src/server/stdio.test.ts | 102 - typescript-sdk/src/server/stdio.ts | 92 - .../src/server/streamableHttp.test.ts | 2148 ------ typescript-sdk/src/server/streamableHttp.ts | 807 -- typescript-sdk/src/server/title.test.ts | 217 - typescript-sdk/src/shared/auth-utils.test.ts | 90 - typescript-sdk/src/shared/auth-utils.ts | 55 - typescript-sdk/src/shared/auth.test.ts | 123 - typescript-sdk/src/shared/auth.ts | 234 - typescript-sdk/src/shared/metadataUtils.ts | 29 - .../protocol-transport-handling.test.ts | 187 - typescript-sdk/src/shared/protocol.test.ts | 744 -- typescript-sdk/src/shared/protocol.ts | 708 -- typescript-sdk/src/shared/stdio.test.ts | 35 - typescript-sdk/src/shared/stdio.ts | 39 - typescript-sdk/src/shared/transport.ts | 85 - typescript-sdk/src/shared/uriTemplate.test.ts | 288 - typescript-sdk/src/shared/uriTemplate.ts | 287 - typescript-sdk/src/spec.types.test.ts | 493 -- typescript-sdk/src/types.test.ts | 314 - typescript-sdk/src/types.ts | 1643 ---- typescript-sdk/src/validation/ajv-provider.ts | 97 - .../src/validation/cfworker-provider.ts | 78 - typescript-sdk/src/validation/index.ts | 30 - typescript-sdk/src/validation/types.ts | 52 - .../src/validation/validation.test.ts | 623 -- typescript-sdk/tsconfig.cjs.json | 9 - typescript-sdk/tsconfig.json | 23 - typescript-sdk/tsconfig.prod.json | 7 - 120 files changed, 95 insertions(+), 47781 deletions(-) delete mode 100644 typescript-sdk/.git-blame-ignore-revs delete mode 100644 typescript-sdk/.gitattributes delete mode 100644 typescript-sdk/.github/CODEOWNERS delete mode 100644 typescript-sdk/.github/workflows/main.yml delete mode 100644 typescript-sdk/.gitignore delete mode 100644 typescript-sdk/.npmrc delete mode 100644 typescript-sdk/.prettierignore delete mode 100644 typescript-sdk/.prettierrc.json delete mode 100644 typescript-sdk/CLAUDE.md delete mode 100644 typescript-sdk/CODE_OF_CONDUCT.md delete mode 100644 typescript-sdk/CONTRIBUTING.md delete mode 100644 typescript-sdk/LICENSE delete mode 100644 typescript-sdk/README.md delete mode 100644 typescript-sdk/SECURITY.md delete mode 100644 typescript-sdk/eslint.config.mjs delete mode 100644 typescript-sdk/jest.config.js delete mode 100644 typescript-sdk/package-lock.json delete mode 100644 typescript-sdk/package.json delete mode 100644 typescript-sdk/src/__mocks__/pkce-challenge.ts delete mode 100644 typescript-sdk/src/cli.ts delete mode 100644 typescript-sdk/src/client/auth.test.ts delete mode 100644 typescript-sdk/src/client/auth.ts delete mode 100644 typescript-sdk/src/client/cross-spawn.test.ts delete mode 100644 typescript-sdk/src/client/index.test.ts delete mode 100644 typescript-sdk/src/client/index.ts delete mode 100644 typescript-sdk/src/client/middleware.test.ts delete mode 100644 typescript-sdk/src/client/middleware.ts delete mode 100644 typescript-sdk/src/client/sse.test.ts delete mode 100644 typescript-sdk/src/client/sse.ts delete mode 100644 typescript-sdk/src/client/stdio.test.ts delete mode 100644 typescript-sdk/src/client/stdio.ts delete mode 100644 typescript-sdk/src/client/streamableHttp.test.ts delete mode 100644 typescript-sdk/src/client/streamableHttp.ts delete mode 100644 typescript-sdk/src/client/websocket.ts delete mode 100644 typescript-sdk/src/examples/README.md delete mode 100644 typescript-sdk/src/examples/client/multipleClientsParallel.ts delete mode 100644 typescript-sdk/src/examples/client/parallelToolCallsClient.ts delete mode 100644 typescript-sdk/src/examples/client/simpleOAuthClient.ts delete mode 100644 typescript-sdk/src/examples/client/simpleStreamableHttp.ts delete mode 100644 typescript-sdk/src/examples/client/streamableHttpWithSseFallbackClient.ts delete mode 100644 typescript-sdk/src/examples/server/demoInMemoryOAuthProvider.test.ts delete mode 100644 typescript-sdk/src/examples/server/demoInMemoryOAuthProvider.ts delete mode 100644 typescript-sdk/src/examples/server/elicitationExample.ts delete mode 100644 typescript-sdk/src/examples/server/jsonResponseStreamableHttp.ts delete mode 100644 typescript-sdk/src/examples/server/mcpServerOutputSchema.ts delete mode 100644 typescript-sdk/src/examples/server/simpleSseServer.ts delete mode 100644 typescript-sdk/src/examples/server/simpleStatelessStreamableHttp.ts delete mode 100644 typescript-sdk/src/examples/server/simpleStreamableHttp.ts delete mode 100644 typescript-sdk/src/examples/server/sseAndStreamableHttpCompatibleServer.ts delete mode 100644 typescript-sdk/src/examples/server/standaloneSseWithGetStreamableHttp.ts delete mode 100644 typescript-sdk/src/examples/server/toolWithSampleServer.ts delete mode 100644 typescript-sdk/src/examples/shared/inMemoryEventStore.ts delete mode 100644 typescript-sdk/src/inMemory.test.ts delete mode 100644 typescript-sdk/src/inMemory.ts delete mode 100644 typescript-sdk/src/integration-tests/process-cleanup.test.ts delete mode 100644 typescript-sdk/src/integration-tests/stateManagementStreamableHttp.test.ts delete mode 100644 typescript-sdk/src/integration-tests/taskResumability.test.ts delete mode 100644 typescript-sdk/src/server/auth/clients.ts delete mode 100644 typescript-sdk/src/server/auth/errors.ts delete mode 100644 typescript-sdk/src/server/auth/handlers/authorize.test.ts delete mode 100644 typescript-sdk/src/server/auth/handlers/authorize.ts delete mode 100644 typescript-sdk/src/server/auth/handlers/metadata.test.ts delete mode 100644 typescript-sdk/src/server/auth/handlers/metadata.ts delete mode 100644 typescript-sdk/src/server/auth/handlers/register.test.ts delete mode 100644 typescript-sdk/src/server/auth/handlers/register.ts delete mode 100644 typescript-sdk/src/server/auth/handlers/revoke.test.ts delete mode 100644 typescript-sdk/src/server/auth/handlers/revoke.ts delete mode 100644 typescript-sdk/src/server/auth/handlers/token.test.ts delete mode 100644 typescript-sdk/src/server/auth/handlers/token.ts delete mode 100644 typescript-sdk/src/server/auth/middleware/allowedMethods.test.ts delete mode 100644 typescript-sdk/src/server/auth/middleware/allowedMethods.ts delete mode 100644 typescript-sdk/src/server/auth/middleware/bearerAuth.test.ts delete mode 100644 typescript-sdk/src/server/auth/middleware/bearerAuth.ts delete mode 100644 typescript-sdk/src/server/auth/middleware/clientAuth.test.ts delete mode 100644 typescript-sdk/src/server/auth/middleware/clientAuth.ts delete mode 100644 typescript-sdk/src/server/auth/provider.ts delete mode 100644 typescript-sdk/src/server/auth/providers/proxyProvider.test.ts delete mode 100644 typescript-sdk/src/server/auth/providers/proxyProvider.ts delete mode 100644 typescript-sdk/src/server/auth/router.test.ts delete mode 100644 typescript-sdk/src/server/auth/router.ts delete mode 100644 typescript-sdk/src/server/auth/types.ts delete mode 100644 typescript-sdk/src/server/completable.test.ts delete mode 100644 typescript-sdk/src/server/completable.ts delete mode 100644 typescript-sdk/src/server/elicitation.test.ts delete mode 100644 typescript-sdk/src/server/index.test.ts delete mode 100644 typescript-sdk/src/server/index.ts delete mode 100644 typescript-sdk/src/server/mcp.test.ts delete mode 100644 typescript-sdk/src/server/mcp.ts delete mode 100644 typescript-sdk/src/server/sse.test.ts delete mode 100644 typescript-sdk/src/server/sse.ts delete mode 100644 typescript-sdk/src/server/stdio.test.ts delete mode 100644 typescript-sdk/src/server/stdio.ts delete mode 100644 typescript-sdk/src/server/streamableHttp.test.ts delete mode 100644 typescript-sdk/src/server/streamableHttp.ts delete mode 100644 typescript-sdk/src/server/title.test.ts delete mode 100644 typescript-sdk/src/shared/auth-utils.test.ts delete mode 100644 typescript-sdk/src/shared/auth-utils.ts delete mode 100644 typescript-sdk/src/shared/auth.test.ts delete mode 100644 typescript-sdk/src/shared/auth.ts delete mode 100644 typescript-sdk/src/shared/metadataUtils.ts delete mode 100644 typescript-sdk/src/shared/protocol-transport-handling.test.ts delete mode 100644 typescript-sdk/src/shared/protocol.test.ts delete mode 100644 typescript-sdk/src/shared/protocol.ts delete mode 100644 typescript-sdk/src/shared/stdio.test.ts delete mode 100644 typescript-sdk/src/shared/stdio.ts delete mode 100644 typescript-sdk/src/shared/transport.ts delete mode 100644 typescript-sdk/src/shared/uriTemplate.test.ts delete mode 100644 typescript-sdk/src/shared/uriTemplate.ts delete mode 100644 typescript-sdk/src/spec.types.test.ts delete mode 100644 typescript-sdk/src/types.test.ts delete mode 100644 typescript-sdk/src/types.ts delete mode 100644 typescript-sdk/src/validation/ajv-provider.ts delete mode 100644 typescript-sdk/src/validation/cfworker-provider.ts delete mode 100644 typescript-sdk/src/validation/index.ts delete mode 100644 typescript-sdk/src/validation/types.ts delete mode 100644 typescript-sdk/src/validation/validation.test.ts delete mode 100644 typescript-sdk/tsconfig.cjs.json delete mode 100644 typescript-sdk/tsconfig.json delete mode 100644 typescript-sdk/tsconfig.prod.json diff --git a/python/kicad_interface.py b/python/kicad_interface.py index dc1d84e..e937134 100644 --- a/python/kicad_interface.py +++ b/python/kicad_interface.py @@ -510,7 +510,7 @@ def main(): """Main entry point""" logger.info("Starting KiCAD interface...") interface = KiCADInterface() - + try: logger.info("Processing commands from stdin...") # Process commands from stdin @@ -519,25 +519,103 @@ def main(): # Parse command logger.debug(f"Received input: {line.strip()}") command_data = json.loads(line) - command = command_data.get("command") - params = command_data.get("params", {}) - - if not command: - logger.error("Missing command field") - response = { - "success": False, - "message": "Missing command", - "errorDetails": "The command field is required" - } + + # Check if this is JSON-RPC 2.0 format + if 'jsonrpc' in command_data and command_data['jsonrpc'] == '2.0': + logger.info("Detected JSON-RPC 2.0 format message") + method = command_data.get('method') + params = command_data.get('params', {}) + request_id = command_data.get('id') + + # Handle MCP protocol methods + if method == 'initialize': + logger.info("Handling MCP initialize") + response = { + 'jsonrpc': '2.0', + 'id': request_id, + 'result': { + 'protocolVersion': '2025-06-18', + 'capabilities': { + 'tools': {} + }, + 'serverInfo': { + 'name': 'kicad-mcp-server', + 'version': '0.1.0' + } + } + } + elif method == 'tools/list': + logger.info("Handling MCP tools/list") + # Return list of available tools + tools = [] + for cmd_name in interface.command_routes.keys(): + tools.append({ + 'name': cmd_name, + 'description': f'KiCAD command: {cmd_name}', + 'inputSchema': { + 'type': 'object', + 'properties': {} + } + }) + response = { + 'jsonrpc': '2.0', + 'id': request_id, + 'result': { + 'tools': tools + } + } + elif method == 'tools/call': + logger.info("Handling MCP tools/call") + tool_name = params.get('name') + tool_params = params.get('arguments', {}) + + # Execute the command + result = interface.handle_command(tool_name, tool_params) + + response = { + 'jsonrpc': '2.0', + 'id': request_id, + 'result': { + 'content': [ + { + 'type': 'text', + 'text': json.dumps(result) + } + ] + } + } + else: + logger.error(f"Unknown JSON-RPC method: {method}") + response = { + 'jsonrpc': '2.0', + 'id': request_id, + 'error': { + 'code': -32601, + 'message': f'Method not found: {method}' + } + } else: - # Handle command - response = interface.handle_command(command, params) - + # Handle legacy custom format + logger.info("Detected custom format message") + command = command_data.get("command") + params = command_data.get("params", {}) + + if not command: + logger.error("Missing command field") + response = { + "success": False, + "message": "Missing command", + "errorDetails": "The command field is required" + } + else: + # Handle command + response = interface.handle_command(command, params) + # Send response logger.debug(f"Sending response: {response}") print(json.dumps(response)) sys.stdout.flush() - + except json.JSONDecodeError as e: logger.error(f"Invalid JSON input: {str(e)}") response = { @@ -547,11 +625,11 @@ def main(): } print(json.dumps(response)) sys.stdout.flush() - + except KeyboardInterrupt: logger.info("KiCAD interface stopped") sys.exit(0) - + except Exception as e: logger.error(f"Unexpected error: {str(e)}\n{traceback.format_exc()}") sys.exit(1) diff --git a/typescript-sdk/.git-blame-ignore-revs b/typescript-sdk/.git-blame-ignore-revs deleted file mode 100644 index e69de29..0000000 diff --git a/typescript-sdk/.gitattributes b/typescript-sdk/.gitattributes deleted file mode 100644 index cf96872..0000000 --- a/typescript-sdk/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -package-lock.json linguist-generated=true diff --git a/typescript-sdk/.github/CODEOWNERS b/typescript-sdk/.github/CODEOWNERS deleted file mode 100644 index 596e699..0000000 --- a/typescript-sdk/.github/CODEOWNERS +++ /dev/null @@ -1,11 +0,0 @@ -# TypeScript SDK Code Owners - -# Default owners for everything in the repo -* @modelcontextprotocol/typescript-sdk - -# Auth team owns all auth-related code -/src/server/auth/ @modelcontextprotocol/typescript-sdk-auth -/src/client/auth* @modelcontextprotocol/typescript-sdk-auth -/src/shared/auth* @modelcontextprotocol/typescript-sdk-auth -/src/examples/client/simpleOAuthClient.ts @modelcontextprotocol/typescript-sdk-auth -/src/examples/server/demoInMemoryOAuthProvider.ts @modelcontextprotocol/typescript-sdk-auth \ No newline at end of file diff --git a/typescript-sdk/.github/workflows/main.yml b/typescript-sdk/.github/workflows/main.yml deleted file mode 100644 index 5a7a84b..0000000 --- a/typescript-sdk/.github/workflows/main.yml +++ /dev/null @@ -1,51 +0,0 @@ -on: - push: - branches: - - main - pull_request: - release: - types: [published] - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 18 - cache: npm - - - run: npm ci - - run: npm run build - - run: npm test - - run: npm run lint - - publish: - runs-on: ubuntu-latest - if: github.event_name == 'release' - environment: release - needs: build - - permissions: - contents: read - id-token: write - - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 18 - cache: npm - registry-url: 'https://registry.npmjs.org' - - - run: npm ci - - - run: npm publish --provenance --access public - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/typescript-sdk/.gitignore b/typescript-sdk/.gitignore deleted file mode 100644 index 694735b..0000000 --- a/typescript-sdk/.gitignore +++ /dev/null @@ -1,135 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -.pnpm-debug.log* - -# Diagnostic reports (https://nodejs.org/api/report.html) -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage -*.lcov - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ - -# Snowpack dependency directory (https://snowpack.dev/) -web_modules/ - -# TypeScript cache -*.tsbuildinfo - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional stylelint cache -.stylelintcache - -# Microbundle cache -.rpt2_cache/ -.rts2_cache_cjs/ -.rts2_cache_es/ -.rts2_cache_umd/ - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Output of 'npm run fetch:spec-types' -spec.types.ts - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variable files -.env -.env.development.local -.env.test.local -.env.production.local -.env.local - -# parcel-bundler cache (https://parceljs.org/) -.cache -.parcel-cache - -# Next.js build output -.next -out - -# Nuxt.js build / generate output -.nuxt - -# Gatsby files -.cache/ -# Comment in the public line in if your project uses Gatsby and not Next.js -# https://nextjs.org/blog/next-9-1#public-directory-support -# public - -# vuepress build output -.vuepress/dist - -# vuepress v2.x temp and cache directory -.temp -.cache - -# Docusaurus cache and generated files -.docusaurus - -# Serverless directories -.serverless/ - -# FuseBox cache -.fusebox/ - -# DynamoDB Local files -.dynamodb/ - -# TernJS port file -.tern-port - -# Stores VSCode versions used for testing VSCode extensions -.vscode-test - -# yarn v2 -.yarn/cache -.yarn/unplugged -.yarn/build-state.yml -.yarn/install-state.gz -.pnp.* - -.DS_Store -dist/ diff --git a/typescript-sdk/.npmrc b/typescript-sdk/.npmrc deleted file mode 100644 index 218528f..0000000 --- a/typescript-sdk/.npmrc +++ /dev/null @@ -1 +0,0 @@ -registry = "https://registry.npmjs.org/" diff --git a/typescript-sdk/.prettierignore b/typescript-sdk/.prettierignore deleted file mode 100644 index bacf96e..0000000 --- a/typescript-sdk/.prettierignore +++ /dev/null @@ -1,10 +0,0 @@ -# Ignore artifacts: -build -dist -coverage -*-lock.* -node_modules -**/build -**/dist -.github/CODEOWNERS -pnpm-lock.yaml \ No newline at end of file diff --git a/typescript-sdk/.prettierrc.json b/typescript-sdk/.prettierrc.json deleted file mode 100644 index 840a2c6..0000000 --- a/typescript-sdk/.prettierrc.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "printWidth": 140, - "tabWidth": 4, - "useTabs": false, - "semi": true, - "singleQuote": true, - "trailingComma": "none", - "bracketSpacing": true, - "bracketSameLine": false, - "proseWrap": "always", - "arrowParens": "avoid", - "overrides": [ - { - "files": "**/*.md", - "options": { - "printWidth": 280 - } - } - ] -} diff --git a/typescript-sdk/CLAUDE.md b/typescript-sdk/CLAUDE.md deleted file mode 100644 index 272c4d9..0000000 --- a/typescript-sdk/CLAUDE.md +++ /dev/null @@ -1,28 +0,0 @@ -# MCP TypeScript SDK Guide - -## Build & Test Commands - -```sh -npm run build # Build ESM and CJS versions -npm run lint # Run ESLint -npm test # Run all tests -npx jest path/to/file.test.ts # Run specific test file -npx jest -t "test name" # Run tests matching pattern -``` - -## Code Style Guidelines - -- **TypeScript**: Strict type checking, ES modules, explicit return types -- **Naming**: PascalCase for classes/types, camelCase for functions/variables -- **Files**: Lowercase with hyphens, test files with `.test.ts` suffix -- **Imports**: ES module style, include `.js` extension, group imports logically -- **Error Handling**: Use TypeScript's strict mode, explicit error checking in tests -- **Formatting**: 2-space indentation, semicolons required, single quotes preferred -- **Testing**: Co-locate tests with source files, use descriptive test names -- **Comments**: JSDoc for public APIs, inline comments for complex logic - -## Project Structure - -- `/src`: Source code with client, server, and shared modules -- Tests alongside source files with `.test.ts` suffix -- Node.js >= 18 required diff --git a/typescript-sdk/CODE_OF_CONDUCT.md b/typescript-sdk/CODE_OF_CONDUCT.md deleted file mode 100644 index 62c701a..0000000 --- a/typescript-sdk/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,83 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, -education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our community include: - -- Demonstrating empathy and kindness toward other people -- Being respectful of differing opinions, viewpoints, and experiences -- Giving and gracefully accepting constructive feedback -- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -- Focusing on what is best not just for us as individuals, but for the overall community - -Examples of unacceptable behavior include: - -- The use of sexualized language or imagery, and sexual attention or advances of any kind -- Trolling, insulting or derogatory comments, and personal or political attacks -- Public or private harassment -- Publishing others' private information, such as a physical or email address, without their explicit permission -- Other conduct which could reasonably be considered inappropriate in a professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, -or acting as an appointed representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at . All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of actions. - -**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as -well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is -allowed during this period. Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at . - -Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at . Translations are available at . diff --git a/typescript-sdk/CONTRIBUTING.md b/typescript-sdk/CONTRIBUTING.md deleted file mode 100644 index ace9542..0000000 --- a/typescript-sdk/CONTRIBUTING.md +++ /dev/null @@ -1,50 +0,0 @@ -# Contributing to MCP TypeScript SDK - -We welcome contributions to the Model Context Protocol TypeScript SDK! This document outlines the process for contributing to the project. - -## Getting Started - -1. Fork the repository -2. Clone your fork: `git clone https://github.com/YOUR-USERNAME/typescript-sdk.git` -3. Install dependencies: `npm install` -4. Build the project: `npm run build` -5. Run tests: `npm test` - -## Development Process - -1. Create a new branch for your changes -2. Make your changes -3. Run `npm run lint` to ensure code style compliance -4. Run `npm test` to verify all tests pass -5. Submit a pull request - -## Pull Request Guidelines - -- Follow the existing code style -- Include tests for new functionality -- Update documentation as needed -- Keep changes focused and atomic -- Provide a clear description of changes - -## Running Examples - -- Start the server: `npm run server` -- Run the client: `npm run client` - -## Code of Conduct - -This project follows our [Code of Conduct](CODE_OF_CONDUCT.md). Please review it before contributing. - -## Reporting Issues - -- Use the [GitHub issue tracker](https://github.com/modelcontextprotocol/typescript-sdk/issues) -- Search existing issues before creating a new one -- Provide clear reproduction steps - -## Security Issues - -Please review our [Security Policy](SECURITY.md) for reporting security vulnerabilities. - -## License - -By contributing, you agree that your contributions will be licensed under the MIT License. diff --git a/typescript-sdk/LICENSE b/typescript-sdk/LICENSE deleted file mode 100644 index 3d48435..0000000 --- a/typescript-sdk/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2024 Anthropic, PBC - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/typescript-sdk/README.md b/typescript-sdk/README.md deleted file mode 100644 index 92f5678..0000000 --- a/typescript-sdk/README.md +++ /dev/null @@ -1,1511 +0,0 @@ -# MCP TypeScript SDK ![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fsdk) ![MIT licensed](https://img.shields.io/npm/l/%40modelcontextprotocol%2Fsdk) - -
-Table of Contents - -- [Overview](#overview) -- [Installation](#installation) -- [Quick Start](#quick-start) -- [Core Concepts](#core-concepts) - - [Server](#server) - - [Tools](#tools) - - [Resources](#resources) - - [Prompts](#prompts) - - [Completions](#completions) - - [Display Names and Metadata](#display-names-and-metadata) - - [Sampling](#sampling) -- [Running Your Server](#running-your-server) - - [Streamable HTTP](#streamable-http) - - [stdio](#stdio) - - [Testing and Debugging](#testing-and-debugging) -- [Examples](#examples) - - [Echo Server](#echo-server) - - [SQLite Explorer](#sqlite-explorer) -- [Advanced Usage](#advanced-usage) - - [Dynamic Servers](#dynamic-servers) - - [Improving Network Efficiency with Notification Debouncing](#improving-network-efficiency-with-notification-debouncing) - - [Low-Level Server](#low-level-server) - - [Eliciting User Input](#eliciting-user-input) - - [Writing MCP Clients](#writing-mcp-clients) - - [Proxy Authorization Requests Upstream](#proxy-authorization-requests-upstream) - - [Backwards Compatibility](#backwards-compatibility) -- [Documentation](#documentation) -- [Contributing](#contributing) -- [License](#license) - -
- -## Overview - -The Model Context Protocol allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. This TypeScript SDK implements -[the full MCP specification](https://modelcontextprotocol.io/specification/latest), making it easy to: - -- Create MCP servers that expose resources, prompts and tools -- Build MCP clients that can connect to any MCP server -- Use standard transports like stdio and Streamable HTTP - -## Installation - -```bash -npm install @modelcontextprotocol/sdk -``` - -## Quick Start - -Let's create a simple MCP server that exposes a calculator tool and some data. Save the following as `server.ts`: - -```typescript -import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; -import express from 'express'; -import { z } from 'zod'; - -// Create an MCP server -const server = new McpServer({ - name: 'demo-server', - version: '1.0.0' -}); - -// Add an addition tool -server.registerTool( - 'add', - { - title: 'Addition Tool', - description: 'Add two numbers', - inputSchema: { a: z.number(), b: z.number() }, - outputSchema: { result: z.number() } - }, - async ({ a, b }) => { - const output = { result: a + b }; - return { - content: [{ type: 'text', text: JSON.stringify(output) }], - structuredContent: output - }; - } -); - -// Add a dynamic greeting resource -server.registerResource( - 'greeting', - new ResourceTemplate('greeting://{name}', { list: undefined }), - { - title: 'Greeting Resource', // Display name for UI - description: 'Dynamic greeting generator' - }, - async (uri, { name }) => ({ - contents: [ - { - uri: uri.href, - text: `Hello, ${name}!` - } - ] - }) -); - -// Set up Express and HTTP transport -const app = express(); -app.use(express.json()); - -app.post('/mcp', async (req, res) => { - // Create a new transport for each request to prevent request ID collisions - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: undefined, - enableJsonResponse: true - }); - - res.on('close', () => { - transport.close(); - }); - - await server.connect(transport); - await transport.handleRequest(req, res, req.body); -}); - -const port = parseInt(process.env.PORT || '3000'); -app.listen(port, () => { - console.log(`Demo MCP Server running on http://localhost:${port}/mcp`); -}).on('error', error => { - console.error('Server error:', error); - process.exit(1); -}); -``` - -Install the deps with `npm install @modelcontextprotocol/sdk express zod@3`, and run with `npx -y tsx server.ts`. - -You can connect to it using any MCP client that supports streamable http, such as: - -- [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector): `npx @modelcontextprotocol/inspector` and connect to the streamable HTTP URL `http://localhost:3000/mcp` -- [Claude Code](https://docs.claude.com/en/docs/claude-code/mcp): `claude mcp add --transport http my-server http://localhost:3000/mcp` -- [VS Code](https://code.visualstudio.com/docs/copilot/customization/mcp-servers): `code --add-mcp "{\"name\":\"my-server\",\"type\":\"http\",\"url\":\"http://localhost:3000/mcp\"}"` -- [Cursor](https://cursor.com/docs/context/mcp): Click [this deeplink](cursor://anysphere.cursor-deeplink/mcp/install?name=my-server&config=eyJ1cmwiOiJodHRwOi8vbG9jYWxob3N0OjMwMDAvbWNwIn0%3D) - -Then try asking your agent to add two numbers using its new tool! - -## Core Concepts - -### Server - -The McpServer is your core interface to the MCP protocol. It handles connection management, protocol compliance, and message routing: - -```typescript -const server = new McpServer({ - name: 'my-app', - version: '1.0.0' -}); -``` - -### Tools - -[Tools](https://modelcontextprotocol.io/specification/latest/server/tools) let LLMs take actions through your server. Tools can perform computation, fetch data and have side effects. Tools should be designed to be model-controlled - i.e. AI models will decide which tools to call, -and the arguments. - -```typescript -// Simple tool with parameters -server.registerTool( - 'calculate-bmi', - { - title: 'BMI Calculator', - description: 'Calculate Body Mass Index', - inputSchema: { - weightKg: z.number(), - heightM: z.number() - }, - outputSchema: { bmi: z.number() } - }, - async ({ weightKg, heightM }) => { - const output = { bmi: weightKg / (heightM * heightM) }; - return { - content: [ - { - type: 'text', - text: JSON.stringify(output) - } - ], - structuredContent: output - }; - } -); - -// Async tool with external API call -server.registerTool( - 'fetch-weather', - { - title: 'Weather Fetcher', - description: 'Get weather data for a city', - inputSchema: { city: z.string() }, - outputSchema: { temperature: z.number(), conditions: z.string() } - }, - async ({ city }) => { - const response = await fetch(`https://api.weather.com/${city}`); - const data = await response.json(); - const output = { temperature: data.temp, conditions: data.conditions }; - return { - content: [{ type: 'text', text: JSON.stringify(output) }], - structuredContent: output - }; - } -); - -// Tool that returns ResourceLinks -server.registerTool( - 'list-files', - { - title: 'List Files', - description: 'List project files', - inputSchema: { pattern: z.string() }, - outputSchema: { - count: z.number(), - files: z.array(z.object({ name: z.string(), uri: z.string() })) - } - }, - async ({ pattern }) => { - const output = { - count: 2, - files: [ - { name: 'README.md', uri: 'file:///project/README.md' }, - { name: 'index.ts', uri: 'file:///project/src/index.ts' } - ] - }; - return { - content: [ - { type: 'text', text: JSON.stringify(output) }, - // ResourceLinks let tools return references without file content - { - type: 'resource_link', - uri: 'file:///project/README.md', - name: 'README.md', - mimeType: 'text/markdown', - description: 'A README file' - }, - { - type: 'resource_link', - uri: 'file:///project/src/index.ts', - name: 'index.ts', - mimeType: 'text/typescript', - description: 'An index file' - } - ], - structuredContent: output - }; - } -); -``` - -#### ResourceLinks - -Tools can return `ResourceLink` objects to reference resources without embedding their full content. This can be helpful for performance when dealing with large files or many resources - clients can then selectively read only the resources they need using the provided URIs. - -### Resources - -[Resources](https://modelcontextprotocol.io/specification/latest/server/resources) can also expose data to LLMs, but unlike tools shouldn't perform significant computation or have side effects. - -Resources are designed to be used in an application-driven way, meaning MCP client applications can decide how to expose them. For example, a client could expose a resource picker to the human, or could expose them to the model directly. - -```typescript -// Static resource -server.registerResource( - 'config', - 'config://app', - { - title: 'Application Config', - description: 'Application configuration data', - mimeType: 'text/plain' - }, - async uri => ({ - contents: [ - { - uri: uri.href, - text: 'App configuration here' - } - ] - }) -); - -// Dynamic resource with parameters -server.registerResource( - 'user-profile', - new ResourceTemplate('users://{userId}/profile', { list: undefined }), - { - title: 'User Profile', - description: 'User profile information' - }, - async (uri, { userId }) => ({ - contents: [ - { - uri: uri.href, - text: `Profile data for user ${userId}` - } - ] - }) -); - -// Resource with context-aware completion -server.registerResource( - 'repository', - new ResourceTemplate('github://repos/{owner}/{repo}', { - list: undefined, - complete: { - // Provide intelligent completions based on previously resolved parameters - repo: (value, context) => { - if (context?.arguments?.['owner'] === 'org1') { - return ['project1', 'project2', 'project3'].filter(r => r.startsWith(value)); - } - return ['default-repo'].filter(r => r.startsWith(value)); - } - } - }), - { - title: 'GitHub Repository', - description: 'Repository information' - }, - async (uri, { owner, repo }) => ({ - contents: [ - { - uri: uri.href, - text: `Repository: ${owner}/${repo}` - } - ] - }) -); -``` - -### Prompts - -[Prompts](https://modelcontextprotocol.io/specification/latest/server/prompts) are reusable templates that help humans prompt models to interact with your server. They're designed to be user-driven, and might appear as slash commands in a chat interface. - -```typescript -import { completable } from '@modelcontextprotocol/sdk/server/completable.js'; - -server.registerPrompt( - 'review-code', - { - title: 'Code Review', - description: 'Review code for best practices and potential issues', - argsSchema: { code: z.string() } - }, - ({ code }) => ({ - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please review this code:\n\n${code}` - } - } - ] - }) -); - -// Prompt with context-aware completion -server.registerPrompt( - 'team-greeting', - { - title: 'Team Greeting', - description: 'Generate a greeting for team members', - argsSchema: { - department: completable(z.string(), value => { - // Department suggestions - return ['engineering', 'sales', 'marketing', 'support'].filter(d => d.startsWith(value)); - }), - name: completable(z.string(), (value, context) => { - // Name suggestions based on selected department - const department = context?.arguments?.['department']; - if (department === 'engineering') { - return ['Alice', 'Bob', 'Charlie'].filter(n => n.startsWith(value)); - } else if (department === 'sales') { - return ['David', 'Eve', 'Frank'].filter(n => n.startsWith(value)); - } else if (department === 'marketing') { - return ['Grace', 'Henry', 'Iris'].filter(n => n.startsWith(value)); - } - return ['Guest'].filter(n => n.startsWith(value)); - }) - } - }, - ({ department, name }) => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `Hello ${name}, welcome to the ${department} team!` - } - } - ] - }) -); -``` - -### Completions - -MCP supports argument completions to help users fill in prompt arguments and resource template parameters. See the examples above for [resource completions](#resources) and [prompt completions](#prompts). - -#### Client Usage - -```typescript -// Request completions for any argument -const result = await client.complete({ - ref: { - type: 'ref/prompt', // or "ref/resource" - name: 'example' // or uri: "template://..." - }, - argument: { - name: 'argumentName', - value: 'partial' // What the user has typed so far - }, - context: { - // Optional: Include previously resolved arguments - arguments: { - previousArg: 'value' - } - } -}); -``` - -### Display Names and Metadata - -All resources, tools, and prompts support an optional `title` field for better UI presentation. The `title` is used as a display name (e.g. 'Create a new issue'), while `name` remains the unique identifier (e.g. `create_issue`). - -**Note:** The `register*` methods (`registerTool`, `registerPrompt`, `registerResource`) are the recommended approach for new code. The older methods (`tool`, `prompt`, `resource`) remain available for backwards compatibility. - -#### Title Precedence for Tools - -For tools specifically, there are two ways to specify a title: - -- `title` field in the tool configuration -- `annotations.title` field (when using the older `tool()` method with annotations) - -The precedence order is: `title` → `annotations.title` → `name` - -```typescript -// Using registerTool (recommended) -server.registerTool( - 'my_tool', - { - title: 'My Tool', // This title takes precedence - annotations: { - title: 'Annotation Title' // This is ignored if title is set - } - }, - handler -); - -// Using tool with annotations (older API) -server.tool( - 'my_tool', - 'description', - { - title: 'Annotation Title' // This is used as title - }, - handler -); -``` - -When building clients, use the provided utility to get the appropriate display name: - -```typescript -import { getDisplayName } from '@modelcontextprotocol/sdk/shared/metadataUtils.js'; - -// Automatically handles the precedence: title → annotations.title → name -const displayName = getDisplayName(tool); -``` - -### Sampling - -MCP servers can request LLM completions from connected clients that support sampling. - -```typescript -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; -import express from 'express'; -import { z } from 'zod'; - -const mcpServer = new McpServer({ - name: 'tools-with-sample-server', - version: '1.0.0' -}); - -// Tool that uses LLM sampling to summarize any text -mcpServer.registerTool( - 'summarize', - { - title: 'Text Summarizer', - description: 'Summarize any text using an LLM', - inputSchema: { - text: z.string().describe('Text to summarize') - }, - outputSchema: { summary: z.string() } - }, - async ({ text }) => { - // Call the LLM through MCP sampling - const response = await mcpServer.server.createMessage({ - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please summarize the following text concisely:\n\n${text}` - } - } - ], - maxTokens: 500 - }); - - const summary = response.content.type === 'text' ? response.content.text : 'Unable to generate summary'; - const output = { summary }; - return { - content: [{ type: 'text', text: JSON.stringify(output) }], - structuredContent: output - }; - } -); - -const app = express(); -app.use(express.json()); - -app.post('/mcp', async (req, res) => { - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: undefined, - enableJsonResponse: true - }); - - res.on('close', () => { - transport.close(); - }); - - await mcpServer.connect(transport); - await transport.handleRequest(req, res, req.body); -}); - -const port = parseInt(process.env.PORT || '3000'); -app.listen(port, () => { - console.log(`MCP Server running on http://localhost:${port}/mcp`); -}).on('error', error => { - console.error('Server error:', error); - process.exit(1); -}); -``` - -## Running Your Server - -MCP servers in TypeScript need to be connected to a transport to communicate with clients. How you start the server depends on the choice of transport: - -### Streamable HTTP - -For remote servers, use the Streamable HTTP transport. - -#### Without Session Management (Recommended) - -For most use cases where session management isn't needed: - -```typescript -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; -import express from 'express'; -import { z } from 'zod'; - -const app = express(); -app.use(express.json()); - -// Create the MCP server once (can be reused across requests) -const server = new McpServer({ - name: 'example-server', - version: '1.0.0' -}); - -// Set up your tools, resources, and prompts -server.registerTool( - 'echo', - { - title: 'Echo Tool', - description: 'Echoes back the provided message', - inputSchema: { message: z.string() }, - outputSchema: { echo: z.string() } - }, - async ({ message }) => { - const output = { echo: `Tool echo: ${message}` }; - return { - content: [{ type: 'text', text: JSON.stringify(output) }], - structuredContent: output - }; - } -); - -app.post('/mcp', async (req, res) => { - // In stateless mode, create a new transport for each request to prevent - // request ID collisions. Different clients may use the same JSON-RPC request IDs, - // which would cause responses to be routed to the wrong HTTP connections if - // the transport state is shared. - - try { - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: undefined, - enableJsonResponse: true - }); - - res.on('close', () => { - transport.close(); - }); - - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - } catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); - -const port = parseInt(process.env.PORT || '3000'); -app.listen(port, () => { - console.log(`MCP Server running on http://localhost:${port}/mcp`); -}).on('error', error => { - console.error('Server error:', error); - process.exit(1); -}); -``` - -#### With Session Management - -In some cases, servers need stateful sessions. This can be achieved by [session management](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#session-management) in the MCP protocol. - -```typescript -import express from 'express'; -import { randomUUID } from 'node:crypto'; -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; -import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js'; - -const app = express(); -app.use(express.json()); - -// Map to store transports by session ID -const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}; - -// Handle POST requests for client-to-server communication -app.post('/mcp', async (req, res) => { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id'] as string | undefined; - let transport: StreamableHTTPServerTransport; - - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } else if (!sessionId && isInitializeRequest(req.body)) { - // New initialization request - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - onsessioninitialized: sessionId => { - // Store the transport by session ID - transports[sessionId] = transport; - } - // DNS rebinding protection is disabled by default for backwards compatibility. If you are running this server - // locally, make sure to set: - // enableDnsRebindingProtection: true, - // allowedHosts: ['127.0.0.1'], - }); - - // Clean up transport when closed - transport.onclose = () => { - if (transport.sessionId) { - delete transports[transport.sessionId]; - } - }; - const server = new McpServer({ - name: 'example-server', - version: '1.0.0' - }); - - // ... set up server resources, tools, and prompts ... - - // Connect to the MCP server - await server.connect(transport); - } else { - // Invalid request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - - // Handle the request - await transport.handleRequest(req, res, req.body); -}); - -// Reusable handler for GET and DELETE requests -const handleSessionRequest = async (req: express.Request, res: express.Response) => { - const sessionId = req.headers['mcp-session-id'] as string | undefined; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - - const transport = transports[sessionId]; - await transport.handleRequest(req, res); -}; - -// Handle GET requests for server-to-client notifications via SSE -app.get('/mcp', handleSessionRequest); - -// Handle DELETE requests for session termination -app.delete('/mcp', handleSessionRequest); - -app.listen(3000); -``` - -#### CORS Configuration for Browser-Based Clients - -If you'd like your server to be accessible by browser-based MCP clients, you'll need to configure CORS headers. The `Mcp-Session-Id` header must be exposed for browser clients to access it: - -```typescript -import cors from 'cors'; - -// Add CORS middleware before your MCP routes -app.use( - cors({ - origin: '*', // Configure appropriately for production, for example: - // origin: ['https://your-remote-domain.com', 'https://your-other-remote-domain.com'], - exposedHeaders: ['Mcp-Session-Id'], - allowedHeaders: ['Content-Type', 'mcp-session-id'] - }) -); -``` - -This configuration is necessary because: - -- The MCP streamable HTTP transport uses the `Mcp-Session-Id` header for session management -- Browsers restrict access to response headers unless explicitly exposed via CORS -- Without this configuration, browser-based clients won't be able to read the session ID from initialization responses - -#### DNS Rebinding Protection - -The Streamable HTTP transport includes DNS rebinding protection to prevent security vulnerabilities. By default, this protection is **disabled** for backwards compatibility. - -**Important**: If you are running this server locally, enable DNS rebinding protection: - -```typescript -const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - enableDnsRebindingProtection: true, - - allowedHosts: ['127.0.0.1', ...], - allowedOrigins: ['https://yourdomain.com', 'https://www.yourdomain.com'] -}); -``` - -### stdio - -For local integrations spawned by another process, you can use the stdio transport: - -```typescript -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; - -const server = new McpServer({ - name: 'example-server', - version: '1.0.0' -}); - -// ... set up server resources, tools, and prompts ... - -const transport = new StdioServerTransport(); -await server.connect(transport); -``` - -### Testing and Debugging - -To test your server, you can use the [MCP Inspector](https://github.com/modelcontextprotocol/inspector). See its README for more information. - -## Examples - -### Echo Server - -A simple server demonstrating resources, tools, and prompts: - -```typescript -import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { z } from 'zod'; - -const server = new McpServer({ - name: 'echo-server', - version: '1.0.0' -}); - -server.registerTool( - 'echo', - { - title: 'Echo Tool', - description: 'Echoes back the provided message', - inputSchema: { message: z.string() }, - outputSchema: { echo: z.string() } - }, - async ({ message }) => { - const output = { echo: `Tool echo: ${message}` }; - return { - content: [{ type: 'text', text: JSON.stringify(output) }], - structuredContent: output - }; - } -); - -server.registerResource( - 'echo', - new ResourceTemplate('echo://{message}', { list: undefined }), - { - title: 'Echo Resource', - description: 'Echoes back messages as resources' - }, - async (uri, { message }) => ({ - contents: [ - { - uri: uri.href, - text: `Resource echo: ${message}` - } - ] - }) -); - -server.registerPrompt( - 'echo', - { - title: 'Echo Prompt', - description: 'Creates a prompt to process a message', - argsSchema: { message: z.string() } - }, - ({ message }) => ({ - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please process this message: ${message}` - } - } - ] - }) -); -``` - -### SQLite Explorer - -A more complex example showing database integration: - -```typescript -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import sqlite3 from 'sqlite3'; -import { promisify } from 'util'; -import { z } from 'zod'; - -const server = new McpServer({ - name: 'sqlite-explorer', - version: '1.0.0' -}); - -// Helper to create DB connection -const getDb = () => { - const db = new sqlite3.Database('database.db'); - return { - all: promisify(db.all.bind(db)), - close: promisify(db.close.bind(db)) - }; -}; - -server.registerResource( - 'schema', - 'schema://main', - { - title: 'Database Schema', - description: 'SQLite database schema', - mimeType: 'text/plain' - }, - async uri => { - const db = getDb(); - try { - const tables = await db.all("SELECT sql FROM sqlite_master WHERE type='table'"); - return { - contents: [ - { - uri: uri.href, - text: tables.map((t: { sql: string }) => t.sql).join('\n') - } - ] - }; - } finally { - await db.close(); - } - } -); - -server.registerTool( - 'query', - { - title: 'SQL Query', - description: 'Execute SQL queries on the database', - inputSchema: { sql: z.string() }, - outputSchema: { - rows: z.array(z.record(z.any())), - rowCount: z.number() - } - }, - async ({ sql }) => { - const db = getDb(); - try { - const results = await db.all(sql); - const output = { rows: results, rowCount: results.length }; - return { - content: [ - { - type: 'text', - text: JSON.stringify(output, null, 2) - } - ], - structuredContent: output - }; - } catch (err: unknown) { - const error = err as Error; - return { - content: [ - { - type: 'text', - text: `Error: ${error.message}` - } - ], - isError: true - }; - } finally { - await db.close(); - } - } -); -``` - -## Advanced Usage - -### Dynamic Servers - -If you want to offer an initial set of tools/prompts/resources, but later add additional ones based on user action or external state change, you can add/update/remove them _after_ the Server is connected. This will automatically emit the corresponding `listChanged` notifications: - -```typescript -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; -import express from 'express'; -import { z } from 'zod'; - -const server = new McpServer({ - name: 'Dynamic Example', - version: '1.0.0' -}); - -const listMessageTool = server.registerTool( - 'listMessages', - { - title: 'List Messages', - description: 'List messages in a channel', - inputSchema: { channel: z.string() }, - outputSchema: { messages: z.array(z.string()) } - }, - async ({ channel }) => { - const messages = await listMessages(channel); - const output = { messages }; - return { - content: [{ type: 'text', text: JSON.stringify(output) }], - structuredContent: output - }; - } -); - -const putMessageTool = server.registerTool( - 'putMessage', - { - title: 'Put Message', - description: 'Send a message to a channel', - inputSchema: { channel: z.string(), message: z.string() }, - outputSchema: { success: z.boolean() } - }, - async ({ channel, message }) => { - await putMessage(channel, message); - const output = { success: true }; - return { - content: [{ type: 'text', text: JSON.stringify(output) }], - structuredContent: output - }; - } -); -// Until we upgrade auth, `putMessage` is disabled (won't show up in listTools) -putMessageTool.disable(); - -const upgradeAuthTool = server.registerTool( - 'upgradeAuth', - { - title: 'Upgrade Authorization', - description: 'Upgrade user authorization level', - inputSchema: { permission: z.enum(['write', 'admin']) }, - outputSchema: { - success: z.boolean(), - newPermission: z.string() - } - }, - // Any mutations here will automatically emit `listChanged` notifications - async ({ permission }) => { - const { ok, err, previous } = await upgradeAuthAndStoreToken(permission); - if (!ok) { - return { - content: [{ type: 'text', text: `Error: ${err}` }], - isError: true - }; - } - - // If we previously had read-only access, 'putMessage' is now available - if (previous === 'read') { - putMessageTool.enable(); - } - - if (permission === 'write') { - // If we've just upgraded to 'write' permissions, we can still call 'upgradeAuth' - // but can only upgrade to 'admin'. - upgradeAuthTool.update({ - paramsSchema: { permission: z.enum(['admin']) } // change validation rules - }); - } else { - // If we're now an admin, we no longer have anywhere to upgrade to, so fully remove that tool - upgradeAuthTool.remove(); - } - - const output = { success: true, newPermission: permission }; - return { - content: [{ type: 'text', text: JSON.stringify(output) }], - structuredContent: output - }; - } -); - -// Connect with HTTP transport -const app = express(); -app.use(express.json()); - -app.post('/mcp', async (req, res) => { - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: undefined, - enableJsonResponse: true - }); - - res.on('close', () => { - transport.close(); - }); - - await server.connect(transport); - await transport.handleRequest(req, res, req.body); -}); - -const port = parseInt(process.env.PORT || '3000'); -app.listen(port, () => { - console.log(`MCP Server running on http://localhost:${port}/mcp`); -}); -``` - -### Improving Network Efficiency with Notification Debouncing - -When performing bulk updates that trigger notifications (e.g., enabling or disabling multiple tools in a loop), the SDK can send a large number of messages in a short period. To improve performance and reduce network traffic, you can enable notification debouncing. - -This feature coalesces multiple, rapid calls for the same notification type into a single message. For example, if you disable five tools in a row, only one `notifications/tools/list_changed` message will be sent instead of five. - -> [!IMPORTANT] This feature is designed for "simple" notifications that do not carry unique data in their parameters. To prevent silent data loss, debouncing is **automatically bypassed** for any notification that contains a `params` object or a `relatedRequestId`. Such -> notifications will always be sent immediately. - -This is an opt-in feature configured during server initialization. - -```typescript -import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; - -const server = new McpServer( - { - name: "efficient-server", - version: "1.0.0" - }, - { - // Enable notification debouncing for specific methods - debouncedNotificationMethods: [ - 'notifications/tools/list_changed', - 'notifications/resources/list_changed', - 'notifications/prompts/list_changed' - ] - } -); - -// Now, any rapid changes to tools, resources, or prompts will result -// in a single, consolidated notification for each type. -server.registerTool("tool1", ...).disable(); -server.registerTool("tool2", ...).disable(); -server.registerTool("tool3", ...).disable(); -// Only one 'notifications/tools/list_changed' is sent. -``` - -### Low-Level Server - -For more control, you can use the low-level Server class directly: - -```typescript -import { Server } from '@modelcontextprotocol/sdk/server/index.js'; -import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; -import { ListPromptsRequestSchema, GetPromptRequestSchema } from '@modelcontextprotocol/sdk/types.js'; - -const server = new Server( - { - name: 'example-server', - version: '1.0.0' - }, - { - capabilities: { - prompts: {} - } - } -); - -server.setRequestHandler(ListPromptsRequestSchema, async () => { - return { - prompts: [ - { - name: 'example-prompt', - description: 'An example prompt template', - arguments: [ - { - name: 'arg1', - description: 'Example argument', - required: true - } - ] - } - ] - }; -}); - -server.setRequestHandler(GetPromptRequestSchema, async request => { - if (request.params.name !== 'example-prompt') { - throw new Error('Unknown prompt'); - } - return { - description: 'Example prompt', - messages: [ - { - role: 'user', - content: { - type: 'text', - text: 'Example prompt text' - } - } - ] - }; -}); - -const transport = new StdioServerTransport(); -await server.connect(transport); -``` - -### Eliciting User Input - -MCP servers can request additional information from users through the elicitation feature. This is useful for interactive workflows where the server needs user input or confirmation: - -```typescript -// Server-side: Restaurant booking tool that asks for alternatives -server.registerTool( - 'book-restaurant', - { - title: 'Book Restaurant', - description: 'Book a table at a restaurant', - inputSchema: { - restaurant: z.string(), - date: z.string(), - partySize: z.number() - }, - outputSchema: { - success: z.boolean(), - booking: z - .object({ - restaurant: z.string(), - date: z.string(), - partySize: z.number() - }) - .optional(), - alternatives: z.array(z.string()).optional() - } - }, - async ({ restaurant, date, partySize }) => { - // Check availability - const available = await checkAvailability(restaurant, date, partySize); - - if (!available) { - // Ask user if they want to try alternative dates - const result = await server.server.elicitInput({ - message: `No tables available at ${restaurant} on ${date}. Would you like to check alternative dates?`, - requestedSchema: { - type: 'object', - properties: { - checkAlternatives: { - type: 'boolean', - title: 'Check alternative dates', - description: 'Would you like me to check other dates?' - }, - flexibleDates: { - type: 'string', - title: 'Date flexibility', - description: 'How flexible are your dates?', - enum: ['next_day', 'same_week', 'next_week'], - enumNames: ['Next day', 'Same week', 'Next week'] - } - }, - required: ['checkAlternatives'] - } - }); - - if (result.action === 'accept' && result.content?.checkAlternatives) { - const alternatives = await findAlternatives(restaurant, date, partySize, result.content.flexibleDates as string); - const output = { success: false, alternatives }; - return { - content: [ - { - type: 'text', - text: JSON.stringify(output) - } - ], - structuredContent: output - }; - } - - const output = { success: false }; - return { - content: [ - { - type: 'text', - text: JSON.stringify(output) - } - ], - structuredContent: output - }; - } - - // Book the table - await makeBooking(restaurant, date, partySize); - const output = { - success: true, - booking: { restaurant, date, partySize } - }; - return { - content: [ - { - type: 'text', - text: JSON.stringify(output) - } - ], - structuredContent: output - }; - } -); -``` - -Client-side: Handle elicitation requests - -```typescript -// This is a placeholder - implement based on your UI framework -async function getInputFromUser( - message: string, - schema: any -): Promise<{ - action: 'accept' | 'decline' | 'cancel'; - data?: Record; -}> { - // This should be implemented depending on the app - throw new Error('getInputFromUser must be implemented for your platform'); -} - -client.setRequestHandler(ElicitRequestSchema, async request => { - const userResponse = await getInputFromUser(request.params.message, request.params.requestedSchema); - - return { - action: userResponse.action, - content: userResponse.action === 'accept' ? userResponse.data : undefined - }; -}); -``` - -**Note**: Elicitation requires client support. Clients must declare the `elicitation` capability during initialization. - -### Writing MCP Clients - -The SDK provides a high-level client interface: - -```typescript -import { Client } from '@modelcontextprotocol/sdk/client/index.js'; -import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; - -const transport = new StdioClientTransport({ - command: 'node', - args: ['server.js'] -}); - -const client = new Client({ - name: 'example-client', - version: '1.0.0' -}); - -await client.connect(transport); - -// List prompts -const prompts = await client.listPrompts(); - -// Get a prompt -const prompt = await client.getPrompt({ - name: 'example-prompt', - arguments: { - arg1: 'value' - } -}); - -// List resources -const resources = await client.listResources(); - -// Read a resource -const resource = await client.readResource({ - uri: 'file:///example.txt' -}); - -// Call a tool -const result = await client.callTool({ - name: 'example-tool', - arguments: { - arg1: 'value' - } -}); -``` - -### Proxy Authorization Requests Upstream - -You can proxy OAuth requests to an external authorization provider: - -```typescript -import express from 'express'; -import { ProxyOAuthServerProvider } from '@modelcontextprotocol/sdk/server/auth/providers/proxyProvider.js'; -import { mcpAuthRouter } from '@modelcontextprotocol/sdk/server/auth/router.js'; - -const app = express(); - -const proxyProvider = new ProxyOAuthServerProvider({ - endpoints: { - authorizationUrl: 'https://auth.external.com/oauth2/v1/authorize', - tokenUrl: 'https://auth.external.com/oauth2/v1/token', - revocationUrl: 'https://auth.external.com/oauth2/v1/revoke' - }, - verifyAccessToken: async token => { - return { - token, - clientId: '123', - scopes: ['openid', 'email', 'profile'] - }; - }, - getClient: async client_id => { - return { - client_id, - redirect_uris: ['http://localhost:3000/callback'] - }; - } -}); - -app.use( - mcpAuthRouter({ - provider: proxyProvider, - issuerUrl: new URL('http://auth.external.com'), - baseUrl: new URL('http://mcp.example.com'), - serviceDocumentationUrl: new URL('https://docs.example.com/') - }) -); -``` - -This setup allows you to: - -- Forward OAuth requests to an external provider -- Add custom token validation logic -- Manage client registrations -- Provide custom documentation URLs -- Maintain control over the OAuth flow while delegating to an external provider - -### Backwards Compatibility - -Clients and servers with StreamableHttp transport can maintain [backwards compatibility](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#backwards-compatibility) with the deprecated HTTP+SSE transport (from protocol version 2024-11-05) as follows - -#### Client-Side Compatibility - -For clients that need to work with both Streamable HTTP and older SSE servers: - -```typescript -import { Client } from '@modelcontextprotocol/sdk/client/index.js'; -import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; -import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'; -let client: Client | undefined = undefined; -const baseUrl = new URL(url); -try { - client = new Client({ - name: 'streamable-http-client', - version: '1.0.0' - }); - const transport = new StreamableHTTPClientTransport(new URL(baseUrl)); - await client.connect(transport); - console.log('Connected using Streamable HTTP transport'); -} catch (error) { - // If that fails with a 4xx error, try the older SSE transport - console.log('Streamable HTTP connection failed, falling back to SSE transport'); - client = new Client({ - name: 'sse-client', - version: '1.0.0' - }); - const sseTransport = new SSEClientTransport(baseUrl); - await client.connect(sseTransport); - console.log('Connected using SSE transport'); -} -``` - -#### Server-Side Compatibility - -For servers that need to support both Streamable HTTP and older clients: - -```typescript -import express from 'express'; -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; -import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'; - -const server = new McpServer({ - name: 'backwards-compatible-server', - version: '1.0.0' -}); - -// ... set up server resources, tools, and prompts ... - -const app = express(); -app.use(express.json()); - -// Store transports for each session type -const transports = { - streamable: {} as Record, - sse: {} as Record -}; - -// Modern Streamable HTTP endpoint -app.all('/mcp', async (req, res) => { - // Handle Streamable HTTP transport for modern clients - // Implementation as shown in the "With Session Management" example - // ... -}); - -// Legacy SSE endpoint for older clients -app.get('/sse', async (req, res) => { - // Create SSE transport for legacy clients - const transport = new SSEServerTransport('/messages', res); - transports.sse[transport.sessionId] = transport; - - res.on('close', () => { - delete transports.sse[transport.sessionId]; - }); - - await server.connect(transport); -}); - -// Legacy message endpoint for older clients -app.post('/messages', async (req, res) => { - const sessionId = req.query.sessionId as string; - const transport = transports.sse[sessionId]; - if (transport) { - await transport.handlePostMessage(req, res, req.body); - } else { - res.status(400).send('No transport found for sessionId'); - } -}); - -app.listen(3000); -``` - -**Note**: The SSE transport is now deprecated in favor of Streamable HTTP. New implementations should use Streamable HTTP, and existing SSE implementations should plan to migrate. - -## Documentation - -- [Model Context Protocol documentation](https://modelcontextprotocol.io) -- [MCP Specification](https://spec.modelcontextprotocol.io) -- [Example Servers](https://github.com/modelcontextprotocol/servers) - -## Contributing - -Issues and pull requests are welcome on GitHub at . - -## License - -This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for details. diff --git a/typescript-sdk/SECURITY.md b/typescript-sdk/SECURITY.md deleted file mode 100644 index 6545156..0000000 --- a/typescript-sdk/SECURITY.md +++ /dev/null @@ -1,15 +0,0 @@ -# Security Policy - -Thank you for helping us keep the SDKs and systems they interact with secure. - -## Reporting Security Issues - -This SDK is maintained by [Anthropic](https://www.anthropic.com/) as part of the Model Context Protocol project. - -The security of our systems and user data is Anthropic’s top priority. We appreciate the work of security researchers acting in good faith in identifying and reporting potential vulnerabilities. - -Our security program is managed on HackerOne and we ask that any validated vulnerability in this functionality be reported through their [submission form](https://hackerone.com/anthropic-vdp/reports/new?type=team&report_type=vulnerability). - -## Vulnerability Disclosure Program - -Our Vulnerability Program Guidelines are defined on our [HackerOne program page](https://hackerone.com/anthropic-vdp). diff --git a/typescript-sdk/eslint.config.mjs b/typescript-sdk/eslint.config.mjs deleted file mode 100644 index 5849013..0000000 --- a/typescript-sdk/eslint.config.mjs +++ /dev/null @@ -1,26 +0,0 @@ -// @ts-check - -import eslint from '@eslint/js'; -import tseslint from 'typescript-eslint'; -import eslintConfigPrettier from 'eslint-config-prettier/flat'; - -export default tseslint.config( - eslint.configs.recommended, - ...tseslint.configs.recommended, - { - linterOptions: { - reportUnusedDisableDirectives: false - }, - rules: { - '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }] - } - }, - { - files: ['src/client/**/*.ts', 'src/server/**/*.ts'], - ignores: ['**/*.test.ts'], - rules: { - 'no-console': 'error' - } - }, - eslintConfigPrettier -); diff --git a/typescript-sdk/jest.config.js b/typescript-sdk/jest.config.js deleted file mode 100644 index d15de5a..0000000 --- a/typescript-sdk/jest.config.js +++ /dev/null @@ -1,14 +0,0 @@ -import { createDefaultEsmPreset } from 'ts-jest'; - -const defaultEsmPreset = createDefaultEsmPreset(); - -/** @type {import('ts-jest').JestConfigWithTsJest} **/ -export default { - ...defaultEsmPreset, - moduleNameMapper: { - '^(\\.{1,2}/.*)\\.js$': '$1', - '^pkce-challenge$': '/src/__mocks__/pkce-challenge.ts' - }, - transformIgnorePatterns: ['/node_modules/(?!eventsource)/'], - testPathIgnorePatterns: ['/node_modules/', '/dist/'] -}; diff --git a/typescript-sdk/package-lock.json b/typescript-sdk/package-lock.json deleted file mode 100644 index 0f614d7..0000000 --- a/typescript-sdk/package-lock.json +++ /dev/null @@ -1,6812 +0,0 @@ -{ - "name": "@modelcontextprotocol/sdk", - "version": "1.20.2", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "@modelcontextprotocol/sdk", - "version": "1.20.2", - "license": "MIT", - "dependencies": { - "ajv": "^8.17.1", - "ajv-formats": "^3.0.1", - "content-type": "^1.0.5", - "cors": "^2.8.5", - "cross-spawn": "^7.0.5", - "eventsource": "^3.0.2", - "eventsource-parser": "^3.0.0", - "express": "^5.0.1", - "express-rate-limit": "^7.5.0", - "pkce-challenge": "^5.0.0", - "raw-body": "^3.0.0", - "zod": "^3.23.8", - "zod-to-json-schema": "^3.24.1" - }, - "devDependencies": { - "@cfworker/json-schema": "^4.1.1", - "@eslint/js": "^9.8.0", - "@jest-mock/express": "^3.0.0", - "@types/content-type": "^1.1.8", - "@types/cors": "^2.8.17", - "@types/cross-spawn": "^6.0.6", - "@types/eslint__js": "^8.42.3", - "@types/eventsource": "^1.1.15", - "@types/express": "^5.0.0", - "@types/jest": "^29.5.12", - "@types/node": "^22.0.2", - "@types/supertest": "^6.0.2", - "@types/ws": "^8.5.12", - "eslint": "^9.8.0", - "eslint-config-prettier": "^10.1.8", - "jest": "^29.7.0", - "prettier": "3.6.2", - "supertest": "^7.0.0", - "ts-jest": "^29.2.4", - "tsx": "^4.16.5", - "typescript": "^5.5.4", - "typescript-eslint": "^8.0.0", - "ws": "^8.18.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "@cfworker/json-schema": "^4.1.1", - "ajv": "^8.17.1", - "ajv-formats": "^3.0.1" - }, - "peerDependenciesMeta": { - "@cfworker/json-schema": { - "optional": true - }, - "ajv": { - "optional": true - }, - "ajv-formats": { - "optional": true - } - } - }, - "node_modules/@ampproject/remapping": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", - "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", - "dev": true, - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/code-frame": { - "version": "7.26.2", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz", - "integrity": "sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^7.25.9", - "js-tokens": "^4.0.0", - "picocolors": "^1.0.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/compat-data": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.26.0.tgz", - "integrity": "sha512-qETICbZSLe7uXv9VE8T/RWOdIE5qqyTucOt4zLYMafj2MRO271VGgLd4RACJMeBO37UPWhXiKMBk7YlJ0fOzQA==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.0.tgz", - "integrity": "sha512-i1SLeK+DzNnQ3LL/CswPCa/E5u4lh1k6IAEphON8F+cXt0t9euTshDru0q7/IqMa1PMPz5RnHuHscF8/ZJsStg==", - "dev": true, - "dependencies": { - "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.26.0", - "@babel/generator": "^7.26.0", - "@babel/helper-compilation-targets": "^7.25.9", - "@babel/helper-module-transforms": "^7.26.0", - "@babel/helpers": "^7.26.0", - "@babel/parser": "^7.26.0", - "@babel/template": "^7.25.9", - "@babel/traverse": "^7.25.9", - "@babel/types": "^7.26.0", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/generator": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.26.0.tgz", - "integrity": "sha512-/AIkAmInnWwgEAJGQr9vY0c66Mj6kjkE2ZPB1PurTRaRAh3U+J45sAQMjQDJdh4WbR3l0x5xkimXBKyBXXAu2w==", - "dev": true, - "dependencies": { - "@babel/parser": "^7.26.0", - "@babel/types": "^7.26.0", - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.25", - "jsesc": "^3.0.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.25.9.tgz", - "integrity": "sha512-j9Db8Suy6yV/VHa4qzrj9yZfZxhLWQdVnRlXxmKLYlhWUVB1sB2G5sxuWYXk/whHD9iW76PmNzxZ4UCnTQTVEQ==", - "dev": true, - "dependencies": { - "@babel/compat-data": "^7.25.9", - "@babel/helper-validator-option": "^7.25.9", - "browserslist": "^4.24.0", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-imports": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.25.9.tgz", - "integrity": "sha512-tnUA4RsrmflIM6W6RFTLFSXITtl0wKjgpnLgXyowocVPrbYrLUXSBXDgTs8BlbmIzIdlBySRQjINYs2BAkiLtw==", - "dev": true, - "dependencies": { - "@babel/traverse": "^7.25.9", - "@babel/types": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.26.0.tgz", - "integrity": "sha512-xO+xu6B5K2czEnQye6BHA7DolFFmS3LB7stHZFaOLb1pAwO1HWLS8fXA+eh0A2yIvltPVmx3eNNDBJA2SLHXFw==", - "dev": true, - "dependencies": { - "@babel/helper-module-imports": "^7.25.9", - "@babel/helper-validator-identifier": "^7.25.9", - "@babel/traverse": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-plugin-utils": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.25.9.tgz", - "integrity": "sha512-kSMlyUVdWe25rEsRGviIgOWnoT/nfABVWlqt9N19/dIPWViAOW2s9wznP5tURbs/IDuNk4gPy3YdYRgH3uxhBw==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz", - "integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz", - "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-option": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.25.9.tgz", - "integrity": "sha512-e/zv1co8pp55dNdEcCynfj9X7nyUKUXoUEwfXqaZt0omVOmDe9oOTdKStH4GmAw6zxMFs50ZayuMfHDKlO7Tfw==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.27.0", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.27.0.tgz", - "integrity": "sha512-U5eyP/CTFPuNE3qk+WZMxFkp/4zUzdceQlfzf7DdGdhp+Fezd7HD+i8Y24ZuTMKX3wQBld449jijbGq6OdGNQg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.27.0", - "@babel/types": "^7.27.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.27.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.27.0.tgz", - "integrity": "sha512-iaepho73/2Pz7w2eMS0Q5f83+0RKI7i4xmiYeBmDzfRVbQtTOG7Ts0S4HzJVsTMGI9keU8rNfuZr8DKfSt7Yyg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.27.0" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/plugin-syntax-async-generators": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", - "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-bigint": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", - "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-properties": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", - "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.12.13" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-static-block": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", - "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-attributes": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.26.0.tgz", - "integrity": "sha512-e2dttdsJ1ZTpi3B9UYGLw41hifAubg19AtCu/2I/F1QNVclOBr1dYpTdmdyZ84Xiz43BS/tCUkMAZNLv12Pi+A==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-meta": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", - "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-json-strings": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", - "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.25.9.tgz", - "integrity": "sha512-ld6oezHQMZsZfp6pWtbjaNDF2tiiCYYDqQszHt5VV437lewP9aSi2Of99CK0D0XB21k7FLgnLcmQKyKzynfeAA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-logical-assignment-operators": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", - "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", - "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-numeric-separator": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", - "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-object-rest-spread": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", - "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-catch-binding": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", - "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-chaining": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", - "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-private-property-in-object": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", - "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-top-level-await": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", - "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.25.9.tgz", - "integrity": "sha512-hjMgRy5hb8uJJjUcdWunWVcoi9bGpJp8p5Ol1229PoN6aytsLwNMgmdftO23wnCLMfVmTwZDWMPNq/D1SY60JQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/template": { - "version": "7.27.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.0.tgz", - "integrity": "sha512-2ncevenBqXI6qRMukPlXwHKHchC7RyMuu4xv5JBXRfOGVcTy1mXCD12qrp7Jsoxll1EV3+9sE4GugBVRjT2jFA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.26.2", - "@babel/parser": "^7.27.0", - "@babel/types": "^7.27.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.25.9.tgz", - "integrity": "sha512-ZCuvfwOwlz/bawvAuvcj8rrithP2/N55Tzz342AkTvq4qaWbGfmCk/tKhNaV2cthijKrPAA8SRJV5WWe7IBMJw==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.25.9", - "@babel/generator": "^7.25.9", - "@babel/parser": "^7.25.9", - "@babel/template": "^7.25.9", - "@babel/types": "^7.25.9", - "debug": "^4.3.1", - "globals": "^11.1.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse/node_modules/globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/types": { - "version": "7.27.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.27.0.tgz", - "integrity": "sha512-H45s8fVLYjbhFH62dIJ3WtmJ6RSPt/3DRO0ZcT2SUiYiQyz3BLVb9ADEnLl91m74aQPS3AzzeajZHYOalWe3bg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.25.9", - "@babel/helper-validator-identifier": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@bcoe/v8-coverage": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", - "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", - "dev": true - }, - "node_modules/@cfworker/json-schema": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz", - "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.0.tgz", - "integrity": "sha512-O7vun9Sf8DFjH2UtqK8Ku3LkquL9SZL8OLY1T5NZkA34+wG3OQF7cl4Ql8vdNzM6fzBbYfLaiRLIOZ+2FOCgBQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.0.tgz", - "integrity": "sha512-PTyWCYYiU0+1eJKmw21lWtC+d08JDZPQ5g+kFyxP0V+es6VPPSUhM6zk8iImp2jbV6GwjX4pap0JFbUQN65X1g==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.0.tgz", - "integrity": "sha512-grvv8WncGjDSyUBjN9yHXNt+cq0snxXbDxy5pJtzMKGmmpPxeAmAhWxXI+01lU5rwZomDgD3kJwulEnhTRUd6g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.0.tgz", - "integrity": "sha512-m/ix7SfKG5buCnxasr52+LI78SQ+wgdENi9CqyCXwjVR2X4Jkz+BpC3le3AoBPYTC9NHklwngVXvbJ9/Akhrfg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.0.tgz", - "integrity": "sha512-mVwdUb5SRkPayVadIOI78K7aAnPamoeFR2bT5nszFUZ9P8UpK4ratOdYbZZXYSqPKMHfS1wdHCJk1P1EZpRdvw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.0.tgz", - "integrity": "sha512-DgDaYsPWFTS4S3nWpFcMn/33ZZwAAeAFKNHNa1QN0rI4pUjgqf0f7ONmXf6d22tqTY+H9FNdgeaAa+YIFUn2Rg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.0.tgz", - "integrity": "sha512-VN4ocxy6dxefN1MepBx/iD1dH5K8qNtNe227I0mnTRjry8tj5MRk4zprLEdG8WPyAPb93/e4pSgi1SoHdgOa4w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.0.tgz", - "integrity": "sha512-mrSgt7lCh07FY+hDD1TxiTyIHyttn6vnjesnPoVDNmDfOmggTLXRv8Id5fNZey1gl/V2dyVK1VXXqVsQIiAk+A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.0.tgz", - "integrity": "sha512-vkB3IYj2IDo3g9xX7HqhPYxVkNQe8qTK55fraQyTzTX/fxaDtXiEnavv9geOsonh2Fd2RMB+i5cbhu2zMNWJwg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.0.tgz", - "integrity": "sha512-9QAQjTWNDM/Vk2bgBl17yWuZxZNQIF0OUUuPZRKoDtqF2k4EtYbpyiG5/Dk7nqeK6kIJWPYldkOcBqjXjrUlmg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.0.tgz", - "integrity": "sha512-43ET5bHbphBegyeqLb7I1eYn2P/JYGNmzzdidq/w0T8E2SsYL1U6un2NFROFRg1JZLTzdCoRomg8Rvf9M6W6Gg==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.0.tgz", - "integrity": "sha512-fC95c/xyNFueMhClxJmeRIj2yrSMdDfmqJnyOY4ZqsALkDrrKJfIg5NTMSzVBr5YW1jf+l7/cndBfP3MSDpoHw==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.0.tgz", - "integrity": "sha512-nkAMFju7KDW73T1DdH7glcyIptm95a7Le8irTQNO/qtkoyypZAnjchQgooFUDQhNAy4iu08N79W4T4pMBwhPwQ==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.0.tgz", - "integrity": "sha512-NhyOejdhRGS8Iwv+KKR2zTq2PpysF9XqY+Zk77vQHqNbo/PwZCzB5/h7VGuREZm1fixhs4Q/qWRSi5zmAiO4Fw==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.0.tgz", - "integrity": "sha512-5S/rbP5OY+GHLC5qXp1y/Mx//e92L1YDqkiBbO9TQOvuFXM+iDqUNG5XopAnXoRH3FjIUDkeGcY1cgNvnXp/kA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.0.tgz", - "integrity": "sha512-XM2BFsEBz0Fw37V0zU4CXfcfuACMrppsMFKdYY2WuTS3yi8O1nFOhil/xhKTmE1nPmVyvQJjJivgDT+xh8pXJA==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.0.tgz", - "integrity": "sha512-9yl91rHw/cpwMCNytUDxwj2XjFpxML0y9HAOH9pNVQDpQrBxHy01Dx+vaMu0N1CKa/RzBD2hB4u//nfc+Sd3Cw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.0.tgz", - "integrity": "sha512-RuG4PSMPFfrkH6UwCAqBzauBWTygTvb1nxWasEJooGSJ/NwRw7b2HOwyRTQIU97Hq37l3npXoZGYMy3b3xYvPw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.0.tgz", - "integrity": "sha512-jl+qisSB5jk01N5f7sPCsBENCOlPiS/xptD5yxOx2oqQfyourJwIKLRA2yqWdifj3owQZCL2sn6o08dBzZGQzA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.0.tgz", - "integrity": "sha512-21sUNbq2r84YE+SJDfaQRvdgznTD8Xc0oc3p3iW/a1EVWeNj/SdUCbm5U0itZPQYRuRTW20fPMWMpcrciH2EJw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.0.tgz", - "integrity": "sha512-2gwwriSMPcCFRlPlKx3zLQhfN/2WjJ2NSlg5TKLQOJdV0mSxIcYNTMhk3H3ulL/cak+Xj0lY1Ym9ysDV1igceg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.0.tgz", - "integrity": "sha512-bxI7ThgLzPrPz484/S9jLlvUAHYMzy6I0XiU1ZMeAEOBcS0VePBFxh1JjTQt3Xiat5b6Oh4x7UC7IwKQKIJRIg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.0.tgz", - "integrity": "sha512-ZUAc2YK6JW89xTbXvftxdnYy3m4iHIkDtK3CLce8wg8M2L+YZhIvO1DKpxrd0Yr59AeNNkTiic9YLf6FTtXWMw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.0.tgz", - "integrity": "sha512-eSNxISBu8XweVEWG31/JzjkIGbGIJN/TrRoiSVZwZ6pkC6VX4Im/WV2cz559/TXLcYbcrDN8JtKgd9DJVIo8GA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.0.tgz", - "integrity": "sha512-ZENoHJBxA20C2zFzh6AI4fT6RraMzjYw4xKWemRTRmRVtN9c5DcH9r/f2ihEkMjOW5eGgrwCslG/+Y/3bL+DHQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz", - "integrity": "sha512-s3O3waFUrMV8P/XaF/+ZTp1X9XBZW1a4B97ZnjQF2KYWaFD2A8KyFBsrsfSjEmjn3RGWAIuvlneuZm3CUK3jbA==", - "dev": true, - "dependencies": { - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" - } - }, - "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "dev": true, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@eslint-community/regexpp": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.1.tgz", - "integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==", - "dev": true, - "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" - } - }, - "node_modules/@eslint/config-array": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.18.0.tgz", - "integrity": "sha512-fTxvnS1sRMu3+JjXwJG0j/i4RT9u4qJ+lqS/yCGap4lH4zZGzQ7tu+xZqQmcMZq5OBZDL4QRxQzRjkWcGt8IVw==", - "dev": true, - "dependencies": { - "@eslint/object-schema": "^2.1.4", - "debug": "^4.3.1", - "minimatch": "^3.1.2" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/core": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.7.0.tgz", - "integrity": "sha512-xp5Jirz5DyPYlPiKat8jaq0EmYvDXKKpzTbxXMpT9eqlRJkRKIz9AGMdlvYjih+im+QlhWrpvVjl8IPC/lHlUw==", - "dev": true, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/eslintrc": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.1.0.tgz", - "integrity": "sha512-4Bfj15dVJdoy3RfZmmo86RK1Fwzn6SstsvK9JS+BaVKqC6QQQQyXekNaC+g+LKNgkQ+2VhGAzm6hO40AhMR3zQ==", - "dev": true, - "dependencies": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^10.0.1", - "globals": "^14.0.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.1.2", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@eslint/eslintrc/node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@eslint/js": { - "version": "9.13.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.13.0.tgz", - "integrity": "sha512-IFLyoY4d72Z5y/6o/BazFBezupzI/taV8sGumxTAVw3lXG9A6md1Dc34T9s1FoD/an9pJH8RHbAxsaEbBed9lA==", - "dev": true, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/object-schema": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.4.tgz", - "integrity": "sha512-BsWiH1yFGjXXS2yvrf5LyuoSIIbPrGUWob917o+BTKuZ7qJdxX8aJLRxs1fS9n6r7vESrq1OUqb68dANcFXuQQ==", - "dev": true, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/plugin-kit": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.2.3.tgz", - "integrity": "sha512-2b/g5hRmpbb1o4GnTZax9N9m0FXzz9OV42ZzI4rDDMDuHUqigAiQCEWChBWCY4ztAGVRjoWT19v0yMmc5/L5kA==", - "dev": true, - "dependencies": { - "levn": "^0.4.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@humanfs/core": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.0.tgz", - "integrity": "sha512-2cbWIHbZVEweE853g8jymffCA+NCMiuqeECeBBLm8dg2oFdjuGJhgN4UAbI+6v0CKbbhvtXA4qV8YR5Ji86nmw==", - "dev": true, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/node": { - "version": "0.16.5", - "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.5.tgz", - "integrity": "sha512-KSPA4umqSG4LHYRodq31VDwKAvaTF4xmVlzM8Aeh4PlU1JQ3IG0wiA8C25d3RQ9nJyM3mBHyI53K06VVL/oFFg==", - "dev": true, - "dependencies": { - "@humanfs/core": "^0.19.0", - "@humanwhocodes/retry": "^0.3.0" - }, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "dev": true, - "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@humanwhocodes/retry": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.1.tgz", - "integrity": "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA==", - "dev": true, - "engines": { - "node": ">=18.18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", - "dev": true, - "dependencies": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "dependencies": { - "sprintf-js": "~1.0.2" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "dev": true, - "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/schema": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", - "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/@jest-mock/express": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@jest-mock/express/-/express-3.0.0.tgz", - "integrity": "sha512-omOl6bh4EOUbp9bvcPSBZKaG8nAtBlhVSUhLx0brHrNpEDn+fMtQp58NkhdY3OoUfXjb7go/EcSYwk+H1BVLdg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/express": "^5.0.0" - } - }, - "node_modules/@jest/console": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", - "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/core": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", - "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", - "dev": true, - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/reporters": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-changed-files": "^29.7.0", - "jest-config": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-resolve-dependencies": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "jest-watcher": "^29.7.0", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/environment": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", - "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", - "dev": true, - "dependencies": { - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-mock": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", - "dev": true, - "dependencies": { - "expect": "^29.7.0", - "jest-snapshot": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/expect-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", - "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", - "dev": true, - "dependencies": { - "jest-get-type": "^29.6.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/fake-timers": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", - "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "@sinonjs/fake-timers": "^10.0.2", - "@types/node": "*", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/globals": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", - "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/types": "^29.6.3", - "jest-mock": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/reporters": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", - "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", - "dev": true, - "dependencies": { - "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "@types/node": "*", - "chalk": "^4.0.0", - "collect-v8-coverage": "^1.0.0", - "exit": "^0.1.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^6.0.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.0", - "istanbul-reports": "^3.1.3", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "slash": "^3.0.0", - "string-length": "^4.0.1", - "strip-ansi": "^6.0.0", - "v8-to-istanbul": "^9.0.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/schemas": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", - "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", - "dev": true, - "dependencies": { - "@sinclair/typebox": "^0.27.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/source-map": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", - "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", - "dev": true, - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.18", - "callsites": "^3.0.0", - "graceful-fs": "^4.2.9" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/test-result": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", - "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", - "dev": true, - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "collect-v8-coverage": "^1.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/test-sequencer": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", - "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", - "dev": true, - "dependencies": { - "@jest/test-result": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/transform": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", - "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "babel-plugin-istanbul": "^6.1.1", - "chalk": "^4.0.0", - "convert-source-map": "^2.0.0", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "micromatch": "^4.0.4", - "pirates": "^4.0.4", - "slash": "^3.0.0", - "write-file-atomic": "^4.0.2" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/types": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", - "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", - "dev": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", - "@types/node": "*", - "@types/yargs": "^17.0.8", - "chalk": "^4.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", - "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", - "dev": true, - "dependencies": { - "@jridgewell/set-array": "^1.2.1", - "@jridgewell/sourcemap-codec": "^1.4.10", - "@jridgewell/trace-mapping": "^0.3.24" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/set-array": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", - "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", - "dev": true, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", - "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", - "dev": true - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.25", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", - "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", - "dev": true, - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@paralleldrive/cuid2": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.2.2.tgz", - "integrity": "sha512-ZOBkgDwEdoYVlSeRbYYXs0S9MejQofiVYoTbKzy/6GQa39/q5tQU2IX46+shYnUkpEl3wc+J6wRlar7r2EK2xA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@noble/hashes": "^1.1.5" - } - }, - "node_modules/@sinclair/typebox": { - "version": "0.27.8", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", - "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", - "dev": true - }, - "node_modules/@sinonjs/commons": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", - "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", - "dev": true, - "dependencies": { - "type-detect": "4.0.8" - } - }, - "node_modules/@sinonjs/fake-timers": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", - "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", - "dev": true, - "dependencies": { - "@sinonjs/commons": "^3.0.0" - } - }, - "node_modules/@types/babel__core": { - "version": "7.20.5", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", - "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", - "dev": true, - "dependencies": { - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "node_modules/@types/babel__generator": { - "version": "7.6.8", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.8.tgz", - "integrity": "sha512-ASsj+tpEDsEiFr1arWrlN6V3mdfjRMZt6LtK/Vp/kreFLnr5QH5+DhvD5nINYZXzwJvXeGq+05iUXcAzVrqWtw==", - "dev": true, - "dependencies": { - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__template": { - "version": "7.4.4", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", - "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", - "dev": true, - "dependencies": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__traverse": { - "version": "7.20.6", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.6.tgz", - "integrity": "sha512-r1bzfrm0tomOI8g1SzvCaQHo6Lcv6zu0EA+W2kHrt8dyrHQxGzBBL4kdkzIS+jBMV+EYcMAEAqXqYaLJq5rOZg==", - "dev": true, - "dependencies": { - "@babel/types": "^7.20.7" - } - }, - "node_modules/@types/body-parser": { - "version": "1.19.5", - "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", - "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/connect": "*", - "@types/node": "*" - } - }, - "node_modules/@types/connect": { - "version": "3.4.38", - "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", - "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", - "dev": true, - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/content-type": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/@types/content-type/-/content-type-1.1.8.tgz", - "integrity": "sha512-1tBhmVUeso3+ahfyaKluXe38p+94lovUZdoVfQ3OnJo9uJC42JT7CBoN3k9HYhAae+GwiBYmHu+N9FZhOG+2Pg==", - "dev": true - }, - "node_modules/@types/cookiejar": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@types/cookiejar/-/cookiejar-2.1.5.tgz", - "integrity": "sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/cors": { - "version": "2.8.17", - "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", - "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/cross-spawn": { - "version": "6.0.6", - "resolved": "https://registry.npmjs.org/@types/cross-spawn/-/cross-spawn-6.0.6.tgz", - "integrity": "sha512-fXRhhUkG4H3TQk5dBhQ7m/JDdSNHKwR2BBia62lhwEIq9xGiQKLxd6LymNhn47SjXhsUEPmxi+PKw2OkW4LLjA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/eslint": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz", - "integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==", - "dev": true, - "dependencies": { - "@types/estree": "*", - "@types/json-schema": "*" - } - }, - "node_modules/@types/eslint__js": { - "version": "8.42.3", - "resolved": "https://registry.npmjs.org/@types/eslint__js/-/eslint__js-8.42.3.tgz", - "integrity": "sha512-alfG737uhmPdnvkrLdZLcEKJ/B8s9Y4hrZ+YAdzUeoArBlSUERA2E87ROfOaS4jd/C45fzOoZzidLc1IPwLqOw==", - "dev": true, - "dependencies": { - "@types/eslint": "*" - } - }, - "node_modules/@types/estree": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", - "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", - "dev": true - }, - "node_modules/@types/eventsource": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/@types/eventsource/-/eventsource-1.1.15.tgz", - "integrity": "sha512-XQmGcbnxUNa06HR3VBVkc9+A2Vpi9ZyLJcdS5dwaQQ/4ZMWFO+5c90FnMUpbtMZwB/FChoYHwuVg8TvkECacTA==", - "dev": true - }, - "node_modules/@types/express": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.0.tgz", - "integrity": "sha512-DvZriSMehGHL1ZNLzi6MidnsDhUZM/x2pRdDIKdwbUNqqwHxMlRdkxtn6/EPKyqKpHqTl/4nRZsRNLpZxZRpPQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/body-parser": "*", - "@types/express-serve-static-core": "^5.0.0", - "@types/qs": "*", - "@types/serve-static": "*" - } - }, - "node_modules/@types/express-serve-static-core": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.0.6.tgz", - "integrity": "sha512-3xhRnjJPkULekpSzgtoNYYcTWgEZkp4myc+Saevii5JPnHNvHMRlBSHDbs7Bh1iPPoVTERHEZXyhyLbMEsExsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "@types/qs": "*", - "@types/range-parser": "*", - "@types/send": "*" - } - }, - "node_modules/@types/graceful-fs": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", - "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", - "dev": true, - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/http-errors": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", - "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", - "dev": true - }, - "node_modules/@types/istanbul-lib-coverage": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", - "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==", - "dev": true - }, - "node_modules/@types/istanbul-lib-report": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz", - "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==", - "dev": true, - "dependencies": { - "@types/istanbul-lib-coverage": "*" - } - }, - "node_modules/@types/istanbul-reports": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz", - "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==", - "dev": true, - "dependencies": { - "@types/istanbul-lib-report": "*" - } - }, - "node_modules/@types/jest": { - "version": "29.5.14", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz", - "integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==", - "dev": true, - "dependencies": { - "expect": "^29.0.0", - "pretty-format": "^29.0.0" - } - }, - "node_modules/@types/json-schema": { - "version": "7.0.15", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", - "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", - "dev": true - }, - "node_modules/@types/methods": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", - "integrity": "sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/mime": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", - "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", - "dev": true - }, - "node_modules/@types/node": { - "version": "22.8.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.8.1.tgz", - "integrity": "sha512-k6Gi8Yyo8EtrNtkHXutUu2corfDf9su95VYVP10aGYMMROM6SAItZi0w1XszA6RtWTHSVp5OeFof37w0IEqCQg==", - "dev": true, - "dependencies": { - "undici-types": "~6.19.8" - } - }, - "node_modules/@types/qs": { - "version": "6.9.18", - "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.18.tgz", - "integrity": "sha512-kK7dgTYDyGqS+e2Q4aK9X3D7q234CIZ1Bv0q/7Z5IwRDoADNU81xXJK/YVyLbLTZCoIwUoDoffFeF+p/eIklAA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/range-parser": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", - "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/send": { - "version": "0.17.4", - "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", - "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", - "dev": true, - "dependencies": { - "@types/mime": "^1", - "@types/node": "*" - } - }, - "node_modules/@types/serve-static": { - "version": "1.15.7", - "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz", - "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==", - "dev": true, - "dependencies": { - "@types/http-errors": "*", - "@types/node": "*", - "@types/send": "*" - } - }, - "node_modules/@types/stack-utils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", - "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", - "dev": true - }, - "node_modules/@types/superagent": { - "version": "8.1.9", - "resolved": "https://registry.npmjs.org/@types/superagent/-/superagent-8.1.9.tgz", - "integrity": "sha512-pTVjI73witn+9ILmoJdajHGW2jkSaOzhiFYF1Rd3EQ94kymLqB9PjD9ISg7WaALC7+dCHT0FGe9T2LktLq/3GQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/cookiejar": "^2.1.5", - "@types/methods": "^1.1.4", - "@types/node": "*", - "form-data": "^4.0.0" - } - }, - "node_modules/@types/supertest": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@types/supertest/-/supertest-6.0.2.tgz", - "integrity": "sha512-137ypx2lk/wTQbW6An6safu9hXmajAifU/s7szAHLN/FeIm5w7yR0Wkl9fdJMRSHwOn4HLAI0DaB2TOORuhPDg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/methods": "^1.1.4", - "@types/superagent": "^8.1.0" - } - }, - "node_modules/@types/ws": { - "version": "8.5.12", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.12.tgz", - "integrity": "sha512-3tPRkv1EtkDpzlgyKyI8pGsGZAGPEaXeu0DOj5DI25Ja91bdAYddYHbADRYVrZMRbfW+1l5YwXVDKohDJNQxkQ==", - "dev": true, - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/yargs": { - "version": "17.0.33", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.33.tgz", - "integrity": "sha512-WpxBCKWPLr4xSsHgz511rFJAM+wS28w2zEO1QDNY5zM/S8ok70NNfztH0xwhqKyaK0OHCbN98LDAZuy1ctxDkA==", - "dev": true, - "dependencies": { - "@types/yargs-parser": "*" - } - }, - "node_modules/@types/yargs-parser": { - "version": "21.0.3", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", - "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", - "dev": true - }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.11.0.tgz", - "integrity": "sha512-KhGn2LjW1PJT2A/GfDpiyOfS4a8xHQv2myUagTM5+zsormOmBlYsnQ6pobJ8XxJmh6hnHwa2Mbe3fPrDJoDhbA==", - "dev": true, - "dependencies": { - "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "8.11.0", - "@typescript-eslint/type-utils": "8.11.0", - "@typescript-eslint/utils": "8.11.0", - "@typescript-eslint/visitor-keys": "8.11.0", - "graphemer": "^1.4.0", - "ignore": "^5.3.1", - "natural-compare": "^1.4.0", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^8.0.0 || ^8.0.0-alpha.0", - "eslint": "^8.57.0 || ^9.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/parser": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.11.0.tgz", - "integrity": "sha512-lmt73NeHdy1Q/2ul295Qy3uninSqi6wQI18XwSpm8w0ZbQXUpjCAWP1Vlv/obudoBiIjJVjlztjQ+d/Md98Yxg==", - "dev": true, - "dependencies": { - "@typescript-eslint/scope-manager": "8.11.0", - "@typescript-eslint/types": "8.11.0", - "@typescript-eslint/typescript-estree": "8.11.0", - "@typescript-eslint/visitor-keys": "8.11.0", - "debug": "^4.3.4" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.11.0.tgz", - "integrity": "sha512-Uholz7tWhXmA4r6epo+vaeV7yjdKy5QFCERMjs1kMVsLRKIrSdM6o21W2He9ftp5PP6aWOVpD5zvrvuHZC0bMQ==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "8.11.0", - "@typescript-eslint/visitor-keys": "8.11.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/type-utils": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.11.0.tgz", - "integrity": "sha512-ItiMfJS6pQU0NIKAaybBKkuVzo6IdnAhPFZA/2Mba/uBjuPQPet/8+zh5GtLHwmuFRShZx+8lhIs7/QeDHflOg==", - "dev": true, - "dependencies": { - "@typescript-eslint/typescript-estree": "8.11.0", - "@typescript-eslint/utils": "8.11.0", - "debug": "^4.3.4", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/types": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.11.0.tgz", - "integrity": "sha512-tn6sNMHf6EBAYMvmPUaKaVeYvhUsrE6x+bXQTxjQRp360h1giATU0WvgeEys1spbvb5R+VpNOZ+XJmjD8wOUHw==", - "dev": true, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.11.0.tgz", - "integrity": "sha512-yHC3s1z1RCHoCz5t06gf7jH24rr3vns08XXhfEqzYpd6Hll3z/3g23JRi0jM8A47UFKNc3u/y5KIMx8Ynbjohg==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "8.11.0", - "@typescript-eslint/visitor-keys": "8.11.0", - "debug": "^4.3.4", - "fast-glob": "^3.3.2", - "is-glob": "^4.0.3", - "minimatch": "^9.0.4", - "semver": "^7.6.0", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", - "dev": true, - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", - "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", - "dev": true, - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { - "version": "7.6.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", - "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@typescript-eslint/utils": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.11.0.tgz", - "integrity": "sha512-CYiX6WZcbXNJV7UNB4PLDIBtSdRmRI/nb0FMyqHPTQD1rMjA0foPLaPUV39C/MxkTd/QKSeX+Gb34PPsDVC35g==", - "dev": true, - "dependencies": { - "@eslint-community/eslint-utils": "^4.4.0", - "@typescript-eslint/scope-manager": "8.11.0", - "@typescript-eslint/types": "8.11.0", - "@typescript-eslint/typescript-estree": "8.11.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0" - } - }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.11.0.tgz", - "integrity": "sha512-EaewX6lxSjRJnc+99+dqzTeoDZUfyrA52d2/HRrkI830kgovWsmIiTfmr0NZorzqic7ga+1bS60lRBUgR3n/Bw==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "8.11.0", - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "dev": true, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/accepts": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", - "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", - "license": "MIT", - "dependencies": { - "mime-types": "^3.0.0", - "negotiator": "^1.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/acorn": { - "version": "8.14.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", - "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", - "dev": true, - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true, - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/ajv": { - "version": "8.17.1", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", - "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ajv-formats": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", - "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", - "license": "MIT", - "dependencies": { - "ajv": "^8.0.0" - }, - "peerDependencies": { - "ajv": "^8.0.0" - }, - "peerDependenciesMeta": { - "ajv": { - "optional": true - } - } - }, - "node_modules/ansi-escapes": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", - "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", - "dev": true, - "dependencies": { - "type-fest": "^0.21.3" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true - }, - "node_modules/asap": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", - "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", - "dev": true, - "license": "MIT" - }, - "node_modules/async": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", - "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", - "dev": true - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/babel-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", - "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", - "dev": true, - "dependencies": { - "@jest/transform": "^29.7.0", - "@types/babel__core": "^7.1.14", - "babel-plugin-istanbul": "^6.1.1", - "babel-preset-jest": "^29.6.3", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.8.0" - } - }, - "node_modules/babel-plugin-istanbul": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", - "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.0.0", - "@istanbuljs/load-nyc-config": "^1.0.0", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-instrument": "^5.0.4", - "test-exclude": "^6.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", - "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, - "dependencies": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-jest-hoist": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", - "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", - "dev": true, - "dependencies": { - "@babel/template": "^7.3.3", - "@babel/types": "^7.3.3", - "@types/babel__core": "^7.1.14", - "@types/babel__traverse": "^7.0.6" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/babel-preset-current-node-syntax": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.1.0.tgz", - "integrity": "sha512-ldYss8SbBlWva1bs28q78Ju5Zq1F+8BrqBZZ0VFhLBvhh6lCpC2o3gDJi/5DRLs9FgYZCnmPYIVFU4lRXCkyUw==", - "dev": true, - "dependencies": { - "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.12.13", - "@babel/plugin-syntax-class-static-block": "^7.14.5", - "@babel/plugin-syntax-import-attributes": "^7.24.7", - "@babel/plugin-syntax-import-meta": "^7.10.4", - "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.10.4", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-private-property-in-object": "^7.14.5", - "@babel/plugin-syntax-top-level-await": "^7.14.5" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/babel-preset-jest": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", - "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", - "dev": true, - "dependencies": { - "babel-plugin-jest-hoist": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true - }, - "node_modules/body-parser": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.1.0.tgz", - "integrity": "sha512-/hPxh61E+ll0Ujp24Ilm64cykicul1ypfwjVttduAiEdtnJFvLePSrIPk+HMImtNv5270wOGCb1Tns2rybMkoQ==", - "license": "MIT", - "dependencies": { - "bytes": "^3.1.2", - "content-type": "^1.0.5", - "debug": "^4.4.0", - "http-errors": "^2.0.0", - "iconv-lite": "^0.5.2", - "on-finished": "^2.4.1", - "qs": "^6.14.0", - "raw-body": "^3.0.0", - "type-is": "^2.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/body-parser/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/body-parser/node_modules/qs": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", - "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/browserslist": { - "version": "4.24.2", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.2.tgz", - "integrity": "sha512-ZIc+Q62revdMcqC6aChtW4jz3My3klmCO1fEmINZY/8J3EpBg5/A/D0AKmBveUh6pgoeycoMkVMko84tuYS+Gg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "dependencies": { - "caniuse-lite": "^1.0.30001669", - "electron-to-chromium": "^1.5.41", - "node-releases": "^2.0.18", - "update-browserslist-db": "^1.1.1" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/bs-logger": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", - "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", - "dev": true, - "dependencies": { - "fast-json-stable-stringify": "2.x" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/bser": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", - "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", - "dev": true, - "dependencies": { - "node-int64": "^0.4.0" - } - }, - "node_modules/buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", - "dev": true - }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/call-bound": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.3.tgz", - "integrity": "sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "get-intrinsic": "^1.2.6" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001673", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001673.tgz", - "integrity": "sha512-WTrjUCSMp3LYX0nE12ECkV0a+e6LC85E0Auz75555/qr78Oc8YWhEPNfDd6SHdtlCMSzqtuXY0uyEMNRcsKpKw==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ] - }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/char-regex": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", - "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "dev": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "engines": { - "node": ">=8" - } - }, - "node_modules/cjs-module-lexer": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.1.tgz", - "integrity": "sha512-cuSVIHi9/9E/+821Qjdvngor+xpnlwnuwIyZOaLmHBVdXL+gP+I6QQB9VkO7RI77YIcTV+S1W9AreJ5eN63JBA==", - "dev": true - }, - "node_modules/cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", - "dev": true, - "engines": { - "iojs": ">= 1.0.0", - "node": ">= 0.12.0" - } - }, - "node_modules/collect-v8-coverage": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.2.tgz", - "integrity": "sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==", - "dev": true - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, - "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/component-emitter": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.1.tgz", - "integrity": "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true - }, - "node_modules/content-disposition": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz", - "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==", - "license": "MIT", - "dependencies": { - "safe-buffer": "5.2.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true - }, - "node_modules/cookie": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", - "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", - "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", - "license": "MIT", - "engines": { - "node": ">=6.6.0" - } - }, - "node_modules/cookiejar": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz", - "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==", - "dev": true, - "license": "MIT" - }, - "node_modules/cors": { - "version": "2.8.5", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", - "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", - "license": "MIT", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/create-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", - "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "prompts": "^2.0.1" - }, - "bin": { - "create-jest": "bin/create-jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/cross-spawn": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.5.tgz", - "integrity": "sha512-ZVJrKKYunU38/76t0RMOulHOnUcbU9GbpWKAOZ0mhjr7CX6FVrH+4FrAapSOekrgFQ3f/8gwMEuIft0aKq6Hug==", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/debug": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", - "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/dedent": { - "version": "1.5.3", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.3.tgz", - "integrity": "sha512-NHQtfOOW68WD8lgypbLA5oT+Bt0xXJhiYvoR6SmmNXZfpzOGXwdKWmcwG8N7PwVVWV3eF/68nmD9BaJSsTBhyQ==", - "dev": true, - "peerDependencies": { - "babel-plugin-macros": "^3.1.0" - }, - "peerDependenciesMeta": { - "babel-plugin-macros": { - "optional": true - } - } - }, - "node_modules/deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true - }, - "node_modules/deepmerge": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", - "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/destroy": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", - "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", - "license": "MIT", - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/detect-newline": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", - "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/dezalgo": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz", - "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==", - "dev": true, - "license": "ISC", - "dependencies": { - "asap": "^2.0.0", - "wrappy": "1" - } - }, - "node_modules/diff-sequences": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", - "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "license": "MIT" - }, - "node_modules/ejs": { - "version": "3.1.10", - "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", - "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", - "dev": true, - "dependencies": { - "jake": "^10.8.5" - }, - "bin": { - "ejs": "bin/cli.js" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/electron-to-chromium": { - "version": "1.5.47", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.47.tgz", - "integrity": "sha512-zS5Yer0MOYw4rtK2iq43cJagHZ8sXN0jDHDKzB+86gSBSAI4v07S97mcq+Gs2vclAxSh1j7vOAHxSVgduiiuVQ==", - "dev": true - }, - "node_modules/emittery": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", - "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", - "dev": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sindresorhus/emittery?sponsor=1" - } - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "dev": true, - "dependencies": { - "is-arrayish": "^0.2.1" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-set-tostringtag": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", - "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/esbuild": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.0.tgz", - "integrity": "sha512-BXq5mqc8ltbaN34cDqWuYKyNhX8D/Z0J1xdtdQ8UcIIIyJyz+ZMKUt58tF3SrZ85jcfN/PZYhjR5uDQAYNVbuw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.25.0", - "@esbuild/android-arm": "0.25.0", - "@esbuild/android-arm64": "0.25.0", - "@esbuild/android-x64": "0.25.0", - "@esbuild/darwin-arm64": "0.25.0", - "@esbuild/darwin-x64": "0.25.0", - "@esbuild/freebsd-arm64": "0.25.0", - "@esbuild/freebsd-x64": "0.25.0", - "@esbuild/linux-arm": "0.25.0", - "@esbuild/linux-arm64": "0.25.0", - "@esbuild/linux-ia32": "0.25.0", - "@esbuild/linux-loong64": "0.25.0", - "@esbuild/linux-mips64el": "0.25.0", - "@esbuild/linux-ppc64": "0.25.0", - "@esbuild/linux-riscv64": "0.25.0", - "@esbuild/linux-s390x": "0.25.0", - "@esbuild/linux-x64": "0.25.0", - "@esbuild/netbsd-arm64": "0.25.0", - "@esbuild/netbsd-x64": "0.25.0", - "@esbuild/openbsd-arm64": "0.25.0", - "@esbuild/openbsd-x64": "0.25.0", - "@esbuild/sunos-x64": "0.25.0", - "@esbuild/win32-arm64": "0.25.0", - "@esbuild/win32-ia32": "0.25.0", - "@esbuild/win32-x64": "0.25.0" - } - }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT" - }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint": { - "version": "9.13.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.13.0.tgz", - "integrity": "sha512-EYZK6SX6zjFHST/HRytOdA/zE72Cq/bfw45LSyuwrdvcclb/gqV8RRQxywOBEWO2+WDpva6UZa4CcDeJKzUCFA==", - "dev": true, - "dependencies": { - "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.11.0", - "@eslint/config-array": "^0.18.0", - "@eslint/core": "^0.7.0", - "@eslint/eslintrc": "^3.1.0", - "@eslint/js": "9.13.0", - "@eslint/plugin-kit": "^0.2.0", - "@humanfs/node": "^0.16.5", - "@humanwhocodes/module-importer": "^1.0.1", - "@humanwhocodes/retry": "^0.3.1", - "@types/estree": "^1.0.6", - "@types/json-schema": "^7.0.15", - "ajv": "^6.12.4", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", - "debug": "^4.3.2", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^8.1.0", - "eslint-visitor-keys": "^4.1.0", - "espree": "^10.2.0", - "esquery": "^1.5.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^8.0.0", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3", - "text-table": "^0.2.0" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://eslint.org/donate" - }, - "peerDependencies": { - "jiti": "*" - }, - "peerDependenciesMeta": { - "jiti": { - "optional": true - } - } - }, - "node_modules/eslint-config-prettier": { - "version": "10.1.8", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz", - "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==", - "dev": true, - "license": "MIT", - "bin": { - "eslint-config-prettier": "bin/cli.js" - }, - "funding": { - "url": "https://opencollective.com/eslint-config-prettier" - }, - "peerDependencies": { - "eslint": ">=7.0.0" - } - }, - "node_modules/eslint-scope": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.1.0.tgz", - "integrity": "sha512-14dSvlhaVhKKsa9Fx1l8A17s7ah7Ef7wCakJ10LYk6+GYmP9yDti2oq2SEwcyndt6knfcZyhyxwY3i9yL78EQw==", - "dev": true, - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-visitor-keys": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.1.0.tgz", - "integrity": "sha512-Q7lok0mqMUSf5a/AdAZkA5a/gHcO6snwQClVNNvFKCAVlxXucdU8pKydU5ZVZjBx5xr37vGbFFWtLQYreLzrZg==", - "dev": true, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint/node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/eslint/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/espree": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-10.2.0.tgz", - "integrity": "sha512-upbkBJbckcCNBDBDXEbuhjbP68n+scUd3k/U2EkyM9nw+I/jPiL4cLF/Al06CF96wRltFda16sxDFrxsI1v0/g==", - "dev": true, - "dependencies": { - "acorn": "^8.12.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^4.1.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/esquery": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", - "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", - "dev": true, - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/eventsource": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.2.tgz", - "integrity": "sha512-YolzkJNxsTL3tCJMWFxpxtG2sCjbZ4LQUBUrkdaJK0ub0p6lmJt+2+1SwhKjLc652lpH9L/79Ptez972H9tphw==", - "license": "MIT", - "dependencies": { - "eventsource-parser": "^3.0.0" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/eventsource-parser": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.0.tgz", - "integrity": "sha512-T1C0XCUimhxVQzW4zFipdx0SficT651NnkR0ZSH3yQwh+mFMdLfgjABVi4YtMTtaL4s168593DaoaRLMqryavA==", - "license": "MIT", - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", - "dev": true, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", - "dev": true, - "dependencies": { - "@jest/expect-utils": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/express": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/express/-/express-5.0.1.tgz", - "integrity": "sha512-ORF7g6qGnD+YtUG9yx4DFoqCShNMmUKiXuT5oWMHiOvt/4WFbHC6yCwQMTSBMno7AqntNCAzzcnnjowRkTL9eQ==", - "license": "MIT", - "dependencies": { - "accepts": "^2.0.0", - "body-parser": "^2.0.1", - "content-disposition": "^1.0.0", - "content-type": "~1.0.4", - "cookie": "0.7.1", - "cookie-signature": "^1.2.1", - "debug": "4.3.6", - "depd": "2.0.0", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "^2.0.0", - "fresh": "2.0.0", - "http-errors": "2.0.0", - "merge-descriptors": "^2.0.0", - "methods": "~1.1.2", - "mime-types": "^3.0.0", - "on-finished": "2.4.1", - "once": "1.4.0", - "parseurl": "~1.3.3", - "proxy-addr": "~2.0.7", - "qs": "6.13.0", - "range-parser": "~1.2.1", - "router": "^2.0.0", - "safe-buffer": "5.2.1", - "send": "^1.1.0", - "serve-static": "^2.1.0", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "type-is": "^2.0.0", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/express-rate-limit": { - "version": "7.5.0", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.0.tgz", - "integrity": "sha512-eB5zbQh5h+VenMPM3fh+nw1YExi5nMr6HUCR62ELSP11huvxm/Uir1H1QEyTkk5QX6A58pX6NmaTMceKZ0Eodg==", - "license": "MIT", - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://github.com/sponsors/express-rate-limit" - }, - "peerDependencies": { - "express": "^4.11 || 5 || ^5.0.0-beta.1" - } - }, - "node_modules/express/node_modules/debug": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.6.tgz", - "integrity": "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==", - "license": "MIT", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/express/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "license": "MIT" - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" - }, - "node_modules/fast-glob": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", - "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", - "dev": true, - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.4" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-glob/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true - }, - "node_modules/fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true - }, - "node_modules/fast-safe-stringify": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", - "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", - "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/fastq": { - "version": "1.17.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", - "integrity": "sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==", - "dev": true, - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/fb-watchman": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", - "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", - "dev": true, - "dependencies": { - "bser": "2.1.1" - } - }, - "node_modules/file-entry-cache": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", - "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", - "dev": true, - "dependencies": { - "flat-cache": "^4.0.0" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/filelist": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", - "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", - "dev": true, - "dependencies": { - "minimatch": "^5.0.1" - } - }, - "node_modules/filelist/node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", - "dev": true, - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/filelist/node_modules/minimatch": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", - "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", - "dev": true, - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/finalhandler": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.0.0.tgz", - "integrity": "sha512-MX6Zo2adDViYh+GcxxB1dpO43eypOGUOL12rLCOTMQv/DfIbpSJUy4oQIIZhVZkH9e+bZWKMon0XHFEju16tkQ==", - "license": "MIT", - "dependencies": { - "debug": "2.6.9", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "statuses": "2.0.1", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/finalhandler/node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "license": "MIT", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/finalhandler/node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/finalhandler/node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", - "license": "MIT" - }, - "node_modules/find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", - "dev": true, - "dependencies": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/flat-cache": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", - "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", - "dev": true, - "dependencies": { - "flatted": "^3.2.9", - "keyv": "^4.5.4" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/flatted": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.1.tgz", - "integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==", - "dev": true - }, - "node_modules/form-data": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", - "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", - "dev": true, - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/form-data/node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/form-data/node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/formidable": { - "version": "3.5.4", - "resolved": "https://registry.npmjs.org/formidable/-/formidable-3.5.4.tgz", - "integrity": "sha512-YikH+7CUTOtP44ZTnUhR7Ic2UASBPOqmaRkRKxRbywPTe5VxF7RRCck4af9wutiZ/QKM5nME9Bie2fFaPz5Gug==", - "dev": true, - "license": "MIT", - "dependencies": { - "@paralleldrive/cuid2": "^2.2.2", - "dezalgo": "^1.0.4", - "once": "^1.4.0" - }, - "engines": { - "node": ">=14.0.0" - }, - "funding": { - "url": "https://ko-fi.com/tunnckoCore/commissions" - } - }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", - "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, - "node_modules/get-intrinsic": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.7.tgz", - "integrity": "sha512-VW6Pxhsrk0KAOqs3WEd0klDiF/+V7gQOpAvY1jVU/LHmaD/kQO4523aiJuikX/QAKYiW6x8Jh+RJej1almdtCA==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.0.0", - "function-bind": "^1.1.2", - "get-proto": "^1.0.0", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-package-type": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/get-tsconfig": { - "version": "4.8.1", - "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.8.1.tgz", - "integrity": "sha512-k9PN+cFBmaLWtVz29SkUoqU5O0slLuHJXt/2P+tMVFT+phsSGXGkp9t3rQIqdz0e+06EHNGs3oM6ZX1s2zHxRg==", - "dev": true, - "dependencies": { - "resolve-pkg-maps": "^1.0.0" - }, - "funding": { - "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" - } - }, - "node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", - "dev": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/globals": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", - "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", - "dev": true, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true - }, - "node_modules/graphemer": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", - "dev": true - }, - "node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-tostringtag": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-symbols": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", - "dev": true - }, - "node_modules/http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", - "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true, - "engines": { - "node": ">=10.17.0" - } - }, - "node_modules/iconv-lite": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.5.2.tgz", - "integrity": "sha512-kERHXvpSaB4aU3eANwidg79K8FlrN77m8G9V+0vOR3HYaRifrlwMEpT7ZBJqLSEIHnEgJTHcWK82wwLwwKwtag==", - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "dev": true, - "engines": { - "node": ">= 4" - } - }, - "node_modules/import-fresh": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", - "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", - "dev": true, - "dependencies": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/import-local": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", - "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", - "dev": true, - "dependencies": { - "pkg-dir": "^4.2.0", - "resolve-cwd": "^3.0.0" - }, - "bin": { - "import-local-fixture": "fixtures/cli.js" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true - }, - "node_modules/is-core-module": { - "version": "2.15.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz", - "integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==", - "dev": true, - "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-generator-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", - "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-promise": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", - "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", - "license": "MIT" - }, - "node_modules/is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" - }, - "node_modules/istanbul-lib-coverage": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", - "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-instrument": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", - "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", - "dev": true, - "dependencies": { - "@babel/core": "^7.23.9", - "@babel/parser": "^7.23.9", - "@istanbuljs/schema": "^0.1.3", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^7.5.4" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-instrument/node_modules/semver": { - "version": "7.6.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", - "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-report": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", - "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", - "dev": true, - "dependencies": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^4.0.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", - "dev": true, - "dependencies": { - "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-reports": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.7.tgz", - "integrity": "sha512-BewmUXImeuRk2YY0PVbxgKAysvhRPUQE0h5QRM++nVWyubKGV0l8qQ5op8+B2DOmwSe63Jivj0BjkPQVf8fP5g==", - "dev": true, - "dependencies": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/jake": { - "version": "10.9.2", - "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.2.tgz", - "integrity": "sha512-2P4SQ0HrLQ+fw6llpLnOaGAvN2Zu6778SJMrCUwns4fOoG9ayrTiZk3VV8sCPkVZF8ab0zksVpS8FDY5pRCNBA==", - "dev": true, - "dependencies": { - "async": "^3.2.3", - "chalk": "^4.0.2", - "filelist": "^1.0.4", - "minimatch": "^3.1.2" - }, - "bin": { - "jake": "bin/cli.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", - "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", - "dev": true, - "dependencies": { - "@jest/core": "^29.7.0", - "@jest/types": "^29.6.3", - "import-local": "^3.0.2", - "jest-cli": "^29.7.0" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-changed-files": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", - "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", - "dev": true, - "dependencies": { - "execa": "^5.0.0", - "jest-util": "^29.7.0", - "p-limit": "^3.1.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-circus": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", - "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "co": "^4.6.0", - "dedent": "^1.0.0", - "is-generator-fn": "^2.0.0", - "jest-each": "^29.7.0", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "p-limit": "^3.1.0", - "pretty-format": "^29.7.0", - "pure-rand": "^6.0.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-cli": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", - "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", - "dev": true, - "dependencies": { - "@jest/core": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "create-jest": "^29.7.0", - "exit": "^0.1.2", - "import-local": "^3.0.2", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "yargs": "^17.3.1" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-config": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", - "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/test-sequencer": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-jest": "^29.7.0", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "deepmerge": "^4.2.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-circus": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "micromatch": "^4.0.4", - "parse-json": "^5.2.0", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@types/node": "*", - "ts-node": ">=9.0.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "ts-node": { - "optional": true - } - } - }, - "node_modules/jest-diff": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", - "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", - "dev": true, - "dependencies": { - "chalk": "^4.0.0", - "diff-sequences": "^29.6.3", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-docblock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", - "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", - "dev": true, - "dependencies": { - "detect-newline": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-each": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", - "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "jest-util": "^29.7.0", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-environment-node": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", - "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-get-type": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", - "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-haste-map": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", - "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "@types/graceful-fs": "^4.1.3", - "@types/node": "*", - "anymatch": "^3.0.3", - "fb-watchman": "^2.0.0", - "graceful-fs": "^4.2.9", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "micromatch": "^4.0.4", - "walker": "^1.0.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "optionalDependencies": { - "fsevents": "^2.3.2" - } - }, - "node_modules/jest-leak-detector": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", - "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", - "dev": true, - "dependencies": { - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-matcher-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", - "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", - "dev": true, - "dependencies": { - "chalk": "^4.0.0", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-message-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", - "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.12.13", - "@jest/types": "^29.6.3", - "@types/stack-utils": "^2.0.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-mock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", - "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-pnp-resolver": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", - "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", - "dev": true, - "engines": { - "node": ">=6" - }, - "peerDependencies": { - "jest-resolve": "*" - }, - "peerDependenciesMeta": { - "jest-resolve": { - "optional": true - } - } - }, - "node_modules/jest-regex-util": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", - "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-resolve": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", - "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", - "dev": true, - "dependencies": { - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-pnp-resolver": "^1.2.2", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "resolve": "^1.20.0", - "resolve.exports": "^2.0.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-resolve-dependencies": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", - "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", - "dev": true, - "dependencies": { - "jest-regex-util": "^29.6.3", - "jest-snapshot": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runner": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", - "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", - "dev": true, - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/environment": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "graceful-fs": "^4.2.9", - "jest-docblock": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-leak-detector": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-resolve": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-util": "^29.7.0", - "jest-watcher": "^29.7.0", - "jest-worker": "^29.7.0", - "p-limit": "^3.1.0", - "source-map-support": "0.5.13" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runtime": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", - "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/globals": "^29.7.0", - "@jest/source-map": "^29.6.3", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "cjs-module-lexer": "^1.0.0", - "collect-v8-coverage": "^1.0.0", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "slash": "^3.0.0", - "strip-bom": "^4.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-snapshot": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", - "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@babel/generator": "^7.7.2", - "@babel/plugin-syntax-jsx": "^7.7.2", - "@babel/plugin-syntax-typescript": "^7.7.2", - "@babel/types": "^7.3.3", - "@jest/expect-utils": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0", - "chalk": "^4.0.0", - "expect": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "natural-compare": "^1.4.0", - "pretty-format": "^29.7.0", - "semver": "^7.5.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-snapshot/node_modules/semver": { - "version": "7.6.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", - "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/jest-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", - "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-validate": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", - "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "camelcase": "^6.2.0", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "leven": "^3.1.0", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-validate/node_modules/camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/jest-watcher": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", - "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", - "dev": true, - "dependencies": { - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "jest-util": "^29.7.0", - "string-length": "^4.0.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-worker": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", - "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", - "dev": true, - "dependencies": { - "@types/node": "*", - "jest-util": "^29.7.0", - "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-worker/node_modules/supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true - }, - "node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/jsesc": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.0.2.tgz", - "integrity": "sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==", - "dev": true, - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/json-buffer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", - "dev": true - }, - "node_modules/json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true - }, - "node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "license": "MIT" - }, - "node_modules/json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/keyv": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", - "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", - "dev": true, - "dependencies": { - "json-buffer": "3.0.1" - } - }, - "node_modules/kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/leven": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", - "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true - }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "dev": true, - "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/lodash.memoize": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", - "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", - "dev": true - }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true - }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/make-dir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", - "dev": true, - "dependencies": { - "semver": "^7.5.3" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/make-dir/node_modules/semver": { - "version": "7.6.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", - "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true - }, - "node_modules/makeerror": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", - "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", - "dev": true, - "dependencies": { - "tmpl": "1.0.5" - } - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/media-typer": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", - "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/merge-descriptors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", - "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, - "engines": { - "node": ">= 8" - } - }, - "node_modules/methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/mime": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", - "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", - "dev": true, - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/mime-db": { - "version": "1.53.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.53.0.tgz", - "integrity": "sha512-oHlN/w+3MQ3rba9rqFr6V/ypF10LSkdwUysQL7GkXoTgIWeV+tcXGA852TBxH+gsh8UWoyhR1hKcoMJTuWflpg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.0.tgz", - "integrity": "sha512-XqoSHeCGjVClAmoGFG3lVFqQFRIrTVw2OH3axRqAcfaw+gHWIfnASS92AV+Rl/mk0MupgZTRHQOjxY6YVnzK5w==", - "license": "MIT", - "dependencies": { - "mime-db": "^1.53.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" - }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true - }, - "node_modules/negotiator": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", - "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/node-int64": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", - "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", - "dev": true - }, - "node_modules/node-releases": { - "version": "2.0.18", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz", - "integrity": "sha512-d9VeXT4SJ7ZeOqGX6R5EM022wpL+eWPooLI+5UpWn2jCT1aosUQEhQP214x33Wkwx3JQMvIm+tIoVOdodFS40g==", - "dev": true - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "license": "MIT", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, - "dependencies": { - "mimic-fn": "^2.1.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/optionator": { - "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", - "dev": true, - "dependencies": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.5" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dev": true, - "dependencies": { - "p-limit": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, - "dependencies": { - "callsites": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true - }, - "node_modules/path-to-regexp": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", - "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", - "license": "MIT", - "engines": { - "node": ">=16" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true - }, - "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pirates": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", - "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", - "dev": true, - "engines": { - "node": ">= 6" - } - }, - "node_modules/pkce-challenge": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.0.tgz", - "integrity": "sha512-ueGLflrrnvwB3xuo/uGob5pd5FN7l0MsLf0Z87o/UQmRtwjvfylfc9MurIxRAWywCYTgrvpXBcqjV4OfCYGCIQ==", - "license": "MIT", - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, - "dependencies": { - "find-up": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/pkg-dir/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/prettier": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", - "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", - "dev": true, - "license": "MIT", - "bin": { - "prettier": "bin/prettier.cjs" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, - "node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/pretty-format/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/prompts": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", - "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", - "dev": true, - "dependencies": { - "kleur": "^3.0.3", - "sisteransi": "^1.0.5" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/pure-rand": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", - "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/dubzzz" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fast-check" - } - ] - }, - "node_modules/qs": { - "version": "6.13.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", - "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.0.6" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/raw-body": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz", - "integrity": "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==", - "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.6.3", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/raw-body/node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-is": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "dev": true - }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/resolve": { - "version": "1.22.8", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", - "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", - "dev": true, - "dependencies": { - "is-core-module": "^2.13.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", - "dev": true, - "dependencies": { - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/resolve-cwd/node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/resolve-pkg-maps": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", - "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", - "dev": true, - "funding": { - "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" - } - }, - "node_modules/resolve.exports": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.2.tgz", - "integrity": "sha512-X2UW6Nw3n/aMgDVy+0rSqgHlv39WZAlZrXCdnbyEiKm17DSqHX4MmQMaST3FbeWR5FTuRcUwYAziZajji0Y7mg==", - "dev": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", - "dev": true, - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/router": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/router/-/router-2.1.0.tgz", - "integrity": "sha512-/m/NSLxeYEgWNtyC+WtNHCF7jbGxOibVWKnn+1Psff4dJGOfoXP+MuC/f2CwSmyiHdOIzYnYFp4W6GxWfekaLA==", - "license": "MIT", - "dependencies": { - "is-promise": "^4.0.0", - "parseurl": "^1.3.3", - "path-to-regexp": "^8.0.0" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" - }, - "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/send": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/send/-/send-1.1.0.tgz", - "integrity": "sha512-v67WcEouB5GxbTWL/4NeToqcZiAWEq90N888fczVArY8A79J0L4FD7vj5hm3eUMua5EpoQ59wa/oovY6TLvRUA==", - "license": "MIT", - "dependencies": { - "debug": "^4.3.5", - "destroy": "^1.2.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "fresh": "^0.5.2", - "http-errors": "^2.0.0", - "mime-types": "^2.1.35", - "ms": "^2.1.3", - "on-finished": "^2.4.1", - "range-parser": "^1.2.1", - "statuses": "^2.0.1" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/send/node_modules/fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/send/node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/send/node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/serve-static": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.1.0.tgz", - "integrity": "sha512-A3We5UfEjG8Z7VkDv6uItWw6HY2bBSBJT1KtVESn6EOoOr2jAxNhxWCLY3jDE2WcuHXByWju74ck3ZgLwL8xmA==", - "license": "MIT", - "dependencies": { - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "parseurl": "^1.3.3", - "send": "^1.0.0" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "engines": { - "node": ">=8" - } - }, - "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", - "side-channel-map": "^1.0.1", - "side-channel-weakmap": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-map": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", - "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-weakmap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", - "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3", - "side-channel-map": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true - }, - "node_modules/sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", - "dev": true - }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-support": { - "version": "0.5.13", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", - "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", - "dev": true, - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", - "dev": true - }, - "node_modules/stack-utils": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", - "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "dev": true, - "dependencies": { - "escape-string-regexp": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/stack-utils/node_modules/escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/string-length": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", - "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", - "dev": true, - "dependencies": { - "char-regex": "^1.0.2", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-bom": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/superagent": { - "version": "9.0.2", - "resolved": "https://registry.npmjs.org/superagent/-/superagent-9.0.2.tgz", - "integrity": "sha512-xuW7dzkUpcJq7QnhOsnNUgtYp3xRwpt2F7abdRYIpCsAt0hhUqia0EdxyXZQQpNmGtsCzYHryaKSV3q3GJnq7w==", - "dev": true, - "license": "MIT", - "dependencies": { - "component-emitter": "^1.3.0", - "cookiejar": "^2.1.4", - "debug": "^4.3.4", - "fast-safe-stringify": "^2.1.1", - "form-data": "^4.0.0", - "formidable": "^3.5.1", - "methods": "^1.1.2", - "mime": "2.6.0", - "qs": "^6.11.0" - }, - "engines": { - "node": ">=14.18.0" - } - }, - "node_modules/supertest": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/supertest/-/supertest-7.0.0.tgz", - "integrity": "sha512-qlsr7fIC0lSddmA3tzojvzubYxvlGtzumcdHgPwbFWMISQwL22MhM2Y3LNt+6w9Yyx7559VW5ab70dgphm8qQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "methods": "^1.1.2", - "superagent": "^9.0.1" - }, - "engines": { - "node": ">=14.18.0" - } - }, - "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/test-exclude": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", - "dev": true, - "dependencies": { - "@istanbuljs/schema": "^0.1.2", - "glob": "^7.1.4", - "minimatch": "^3.0.4" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true - }, - "node_modules/tmpl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", - "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", - "dev": true - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/ts-api-utils": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.3.0.tgz", - "integrity": "sha512-UQMIo7pb8WRomKR1/+MFVLTroIvDVtMX3K6OUir8ynLyzB8Jeriont2bTAtmNPa1ekAgN7YPDyf6V+ygrdU+eQ==", - "dev": true, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "typescript": ">=4.2.0" - } - }, - "node_modules/ts-jest": { - "version": "29.2.5", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.2.5.tgz", - "integrity": "sha512-KD8zB2aAZrcKIdGk4OwpJggeLcH1FgrICqDSROWqlnJXGCXK4Mn6FcdK2B6670Xr73lHMG1kHw8R87A0ecZ+vA==", - "dev": true, - "dependencies": { - "bs-logger": "^0.2.6", - "ejs": "^3.1.10", - "fast-json-stable-stringify": "^2.1.0", - "jest-util": "^29.0.0", - "json5": "^2.2.3", - "lodash.memoize": "^4.1.2", - "make-error": "^1.3.6", - "semver": "^7.6.3", - "yargs-parser": "^21.1.1" - }, - "bin": { - "ts-jest": "cli.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0" - }, - "peerDependencies": { - "@babel/core": ">=7.0.0-beta.0 <8", - "@jest/transform": "^29.0.0", - "@jest/types": "^29.0.0", - "babel-jest": "^29.0.0", - "jest": "^29.0.0", - "typescript": ">=4.3 <6" - }, - "peerDependenciesMeta": { - "@babel/core": { - "optional": true - }, - "@jest/transform": { - "optional": true - }, - "@jest/types": { - "optional": true - }, - "babel-jest": { - "optional": true - }, - "esbuild": { - "optional": true - } - } - }, - "node_modules/ts-jest/node_modules/semver": { - "version": "7.6.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", - "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/tsx": { - "version": "4.19.3", - "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.19.3.tgz", - "integrity": "sha512-4H8vUNGNjQ4V2EOoGw005+c+dGuPSnhpPBPHBtsZdGZBk/iJb4kguGlPWaZTZ3q5nMtFOEsY0nRDlh9PJyd6SQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "~0.25.0", - "get-tsconfig": "^4.7.5" - }, - "bin": { - "tsx": "dist/cli.mjs" - }, - "engines": { - "node": ">=18.0.0" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - } - }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/type-fest": { - "version": "0.21.3", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", - "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/type-is": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.0.tgz", - "integrity": "sha512-gd0sGezQYCbWSbkZr75mln4YBidWUN60+devscpLF5mtRDUpiaTvKpBNrdaCvel1NdR2k6vclXybU5fBd2i+nw==", - "license": "MIT", - "dependencies": { - "content-type": "^1.0.5", - "media-typer": "^1.1.0", - "mime-types": "^3.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/typescript": { - "version": "5.6.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", - "integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==", - "dev": true, - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/typescript-eslint": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.11.0.tgz", - "integrity": "sha512-cBRGnW3FSlxaYwU8KfAewxFK5uzeOAp0l2KebIlPDOT5olVi65KDG/yjBooPBG0kGW/HLkoz1c/iuBFehcS3IA==", - "dev": true, - "dependencies": { - "@typescript-eslint/eslint-plugin": "8.11.0", - "@typescript-eslint/parser": "8.11.0", - "@typescript-eslint/utils": "8.11.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/undici-types": { - "version": "6.19.8", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", - "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", - "dev": true - }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/update-browserslist-db": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.1.tgz", - "integrity": "sha512-R8UzCaa9Az+38REPiJ1tXlImTJXlVfgHZsglwBD/k6nj76ctsH1E3q4doGrukiLQd3sGQYu56r5+lo5r94l29A==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "dependencies": { - "escalade": "^3.2.0", - "picocolors": "^1.1.0" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "punycode": "^2.1.0" - } - }, - "node_modules/utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/v8-to-istanbul": { - "version": "9.3.0", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", - "integrity": "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==", - "dev": true, - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.12", - "@types/istanbul-lib-coverage": "^2.0.1", - "convert-source-map": "^2.0.0" - }, - "engines": { - "node": ">=10.12.0" - } - }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/walker": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", - "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", - "dev": true, - "dependencies": { - "makeerror": "1.0.12" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/word-wrap": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", - "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" - }, - "node_modules/write-file-atomic": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", - "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", - "dev": true, - "dependencies": { - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.7" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/ws": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", - "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", - "dev": true, - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true - }, - "node_modules/yargs": { - "version": "17.7.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", - "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "dev": true, - "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, - "engines": { - "node": ">=12" - } - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/zod": { - "version": "3.24.1", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.1.tgz", - "integrity": "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, - "node_modules/zod-to-json-schema": { - "version": "3.24.1", - "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.1.tgz", - "integrity": "sha512-3h08nf3Vw3Wl3PK+q3ow/lIil81IT2Oa7YpQyUUDsEWbXveMesdfK1xBd2RhCkynwZndAxixji/7SYJJowr62w==", - "license": "ISC", - "peerDependencies": { - "zod": "^3.24.1" - } - } - } -} diff --git a/typescript-sdk/package.json b/typescript-sdk/package.json deleted file mode 100644 index 22a5b41..0000000 --- a/typescript-sdk/package.json +++ /dev/null @@ -1,128 +0,0 @@ -{ - "name": "@modelcontextprotocol/sdk", - "version": "1.20.2", - "description": "Model Context Protocol implementation for TypeScript", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", - "homepage": "https://modelcontextprotocol.io", - "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", - "type": "module", - "repository": { - "type": "git", - "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "engines": { - "node": ">=18" - }, - "keywords": [ - "modelcontextprotocol", - "mcp" - ], - "exports": { - ".": { - "import": "./dist/esm/index.js", - "require": "./dist/cjs/index.js" - }, - "./client": { - "import": "./dist/esm/client/index.js", - "require": "./dist/cjs/client/index.js" - }, - "./server": { - "import": "./dist/esm/server/index.js", - "require": "./dist/cjs/server/index.js" - }, - "./validation": { - "import": "./dist/esm/validation/index.js", - "require": "./dist/cjs/validation/index.js" - }, - "./validation/ajv": { - "import": "./dist/esm/validation/ajv-provider.js", - "require": "./dist/cjs/validation/ajv-provider.js" - }, - "./validation/cfworker": { - "import": "./dist/esm/validation/cfworker-provider.js", - "require": "./dist/cjs/validation/cfworker-provider.js" - }, - "./*": { - "import": "./dist/esm/*", - "require": "./dist/cjs/*" - } - }, - "typesVersions": { - "*": { - "*": [ - "./dist/esm/*" - ] - } - }, - "files": [ - "dist" - ], - "scripts": { - "fetch:spec-types": "curl -o spec.types.ts https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/refs/heads/main/schema/draft/schema.ts", - "build": "npm run build:esm && npm run build:cjs", - "build:esm": "mkdir -p dist/esm && echo '{\"type\": \"module\"}' > dist/esm/package.json && tsc -p tsconfig.prod.json", - "build:esm:w": "npm run build:esm -- -w", - "build:cjs": "mkdir -p dist/cjs && echo '{\"type\": \"commonjs\"}' > dist/cjs/package.json && tsc -p tsconfig.cjs.json", - "build:cjs:w": "npm run build:cjs -- -w", - "examples:simple-server:w": "tsx --watch src/examples/server/simpleStreamableHttp.ts --oauth", - "prepack": "npm run build:esm && npm run build:cjs", - "lint": "eslint src/ && prettier --check .", - "lint:fix": "eslint src/ --fix && prettier --write .", - "test": "npm run fetch:spec-types && jest", - "start": "npm run server", - "server": "tsx watch --clear-screen=false src/cli.ts server", - "client": "tsx src/cli.ts client" - }, - "dependencies": { - "ajv": "^8.17.1", - "ajv-formats": "^3.0.1", - "content-type": "^1.0.5", - "cors": "^2.8.5", - "cross-spawn": "^7.0.5", - "eventsource": "^3.0.2", - "eventsource-parser": "^3.0.0", - "express": "^5.0.1", - "express-rate-limit": "^7.5.0", - "pkce-challenge": "^5.0.0", - "raw-body": "^3.0.0", - "zod": "^3.23.8", - "zod-to-json-schema": "^3.24.1" - }, - "peerDependencies": { - "@cfworker/json-schema": "^4.1.1" - }, - "peerDependenciesMeta": { - "@cfworker/json-schema": { - "optional": true - } - }, - "devDependencies": { - "@cfworker/json-schema": "^4.1.1", - "@eslint/js": "^9.8.0", - "@jest-mock/express": "^3.0.0", - "@types/content-type": "^1.1.8", - "@types/cors": "^2.8.17", - "@types/cross-spawn": "^6.0.6", - "@types/eslint__js": "^8.42.3", - "@types/eventsource": "^1.1.15", - "@types/express": "^5.0.0", - "@types/jest": "^29.5.12", - "@types/node": "^22.0.2", - "@types/supertest": "^6.0.2", - "@types/ws": "^8.5.12", - "eslint": "^9.8.0", - "eslint-config-prettier": "^10.1.8", - "jest": "^29.7.0", - "prettier": "3.6.2", - "supertest": "^7.0.0", - "ts-jest": "^29.2.4", - "tsx": "^4.16.5", - "typescript": "^5.5.4", - "typescript-eslint": "^8.0.0", - "ws": "^8.18.0" - }, - "resolutions": { - "strip-ansi": "6.0.1" - } -} diff --git a/typescript-sdk/src/__mocks__/pkce-challenge.ts b/typescript-sdk/src/__mocks__/pkce-challenge.ts deleted file mode 100644 index 3dfec41..0000000 --- a/typescript-sdk/src/__mocks__/pkce-challenge.ts +++ /dev/null @@ -1,6 +0,0 @@ -export default function pkceChallenge() { - return { - code_verifier: 'test_verifier', - code_challenge: 'test_challenge' - }; -} diff --git a/typescript-sdk/src/cli.ts b/typescript-sdk/src/cli.ts deleted file mode 100644 index 9676480..0000000 --- a/typescript-sdk/src/cli.ts +++ /dev/null @@ -1,161 +0,0 @@ -import WebSocket from 'ws'; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(global as any).WebSocket = WebSocket; - -import express from 'express'; -import { Client } from './client/index.js'; -import { SSEClientTransport } from './client/sse.js'; -import { StdioClientTransport } from './client/stdio.js'; -import { WebSocketClientTransport } from './client/websocket.js'; -import { Server } from './server/index.js'; -import { SSEServerTransport } from './server/sse.js'; -import { StdioServerTransport } from './server/stdio.js'; -import { ListResourcesResultSchema } from './types.js'; - -async function runClient(url_or_command: string, args: string[]) { - const client = new Client( - { - name: 'mcp-typescript test client', - version: '0.1.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - let clientTransport; - - let url: URL | undefined = undefined; - try { - url = new URL(url_or_command); - } catch { - // Ignore - } - - if (url?.protocol === 'http:' || url?.protocol === 'https:') { - clientTransport = new SSEClientTransport(new URL(url_or_command)); - } else if (url?.protocol === 'ws:' || url?.protocol === 'wss:') { - clientTransport = new WebSocketClientTransport(new URL(url_or_command)); - } else { - clientTransport = new StdioClientTransport({ - command: url_or_command, - args - }); - } - - console.log('Connected to server.'); - - await client.connect(clientTransport); - console.log('Initialized.'); - - await client.request({ method: 'resources/list' }, ListResourcesResultSchema); - - await client.close(); - console.log('Closed.'); -} - -async function runServer(port: number | null) { - if (port !== null) { - const app = express(); - - let servers: Server[] = []; - - app.get('/sse', async (req, res) => { - console.log('Got new SSE connection'); - - const transport = new SSEServerTransport('/message', res); - const server = new Server( - { - name: 'mcp-typescript test server', - version: '0.1.0' - }, - { - capabilities: {} - } - ); - - servers.push(server); - - server.onclose = () => { - console.log('SSE connection closed'); - servers = servers.filter(s => s !== server); - }; - - await server.connect(transport); - }); - - app.post('/message', async (req, res) => { - console.log('Received message'); - - const sessionId = req.query.sessionId as string; - const transport = servers.map(s => s.transport as SSEServerTransport).find(t => t.sessionId === sessionId); - if (!transport) { - res.status(404).send('Session not found'); - return; - } - - await transport.handlePostMessage(req, res); - }); - - app.listen(port, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Server running on http://localhost:${port}/sse`); - }); - } else { - const server = new Server( - { - name: 'mcp-typescript test server', - version: '0.1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - } - } - ); - - const transport = new StdioServerTransport(); - await server.connect(transport); - - console.log('Server running on stdio'); - } -} - -const args = process.argv.slice(2); -const command = args[0]; -switch (command) { - case 'client': - if (args.length < 2) { - console.error('Usage: client [args...]'); - process.exit(1); - } - - runClient(args[1], args.slice(2)).catch(error => { - console.error(error); - process.exit(1); - }); - - break; - - case 'server': { - const port = args[1] ? parseInt(args[1]) : null; - runServer(port).catch(error => { - console.error(error); - process.exit(1); - }); - - break; - } - - default: - console.error('Unrecognized command:', command); -} diff --git a/typescript-sdk/src/client/auth.test.ts b/typescript-sdk/src/client/auth.test.ts deleted file mode 100644 index f2dadbb..0000000 --- a/typescript-sdk/src/client/auth.test.ts +++ /dev/null @@ -1,2446 +0,0 @@ -import { LATEST_PROTOCOL_VERSION } from '../types.js'; -import { - discoverOAuthMetadata, - discoverAuthorizationServerMetadata, - buildDiscoveryUrls, - startAuthorization, - exchangeAuthorization, - refreshAuthorization, - registerClient, - discoverOAuthProtectedResourceMetadata, - extractResourceMetadataUrl, - auth, - type OAuthClientProvider -} from './auth.js'; -import { ServerError } from '../server/auth/errors.js'; -import { AuthorizationServerMetadata } from '../shared/auth.js'; - -// Mock fetch globally -const mockFetch = jest.fn(); -global.fetch = mockFetch; - -describe('OAuth Authorization', () => { - beforeEach(() => { - mockFetch.mockReset(); - }); - - describe('extractResourceMetadataUrl', () => { - it('returns resource metadata url when present', async () => { - const resourceUrl = 'https://resource.example.com/.well-known/oauth-protected-resource'; - const mockResponse = { - headers: { - get: jest.fn(name => (name === 'WWW-Authenticate' ? `Bearer realm="mcp", resource_metadata="${resourceUrl}"` : null)) - } - } as unknown as Response; - - expect(extractResourceMetadataUrl(mockResponse)).toEqual(new URL(resourceUrl)); - }); - - it('returns undefined if not bearer', async () => { - const resourceUrl = 'https://resource.example.com/.well-known/oauth-protected-resource'; - const mockResponse = { - headers: { - get: jest.fn(name => (name === 'WWW-Authenticate' ? `Basic realm="mcp", resource_metadata="${resourceUrl}"` : null)) - } - } as unknown as Response; - - expect(extractResourceMetadataUrl(mockResponse)).toBeUndefined(); - }); - - it('returns undefined if resource_metadata not present', async () => { - const mockResponse = { - headers: { - get: jest.fn(name => (name === 'WWW-Authenticate' ? `Basic realm="mcp"` : null)) - } - } as unknown as Response; - - expect(extractResourceMetadataUrl(mockResponse)).toBeUndefined(); - }); - - it('returns undefined on invalid url', async () => { - const resourceUrl = 'invalid-url'; - const mockResponse = { - headers: { - get: jest.fn(name => (name === 'WWW-Authenticate' ? `Basic realm="mcp", resource_metadata="${resourceUrl}"` : null)) - } - } as unknown as Response; - - expect(extractResourceMetadataUrl(mockResponse)).toBeUndefined(); - }); - }); - - describe('discoverOAuthProtectedResourceMetadata', () => { - const validMetadata = { - resource: 'https://resource.example.com', - authorization_servers: ['https://auth.example.com'] - }; - - it('returns metadata when discovery succeeds', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthProtectedResourceMetadata('https://resource.example.com'); - expect(metadata).toEqual(validMetadata); - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); - const [url] = calls[0]; - expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); - }); - - it('returns metadata when first fetch fails but second without MCP header succeeds', async () => { - // Set up a counter to control behavior - let callCount = 0; - - // Mock implementation that changes behavior based on call count - mockFetch.mockImplementation((_url, _options) => { - callCount++; - - if (callCount === 1) { - // First call with MCP header - fail with TypeError (simulating CORS error) - // We need to use TypeError specifically because that's what the implementation checks for - return Promise.reject(new TypeError('Network error')); - } else { - // Second call without header - succeed - return Promise.resolve({ - ok: true, - status: 200, - json: async () => validMetadata - }); - } - }); - - // Should succeed with the second call - const metadata = await discoverOAuthProtectedResourceMetadata('https://resource.example.com'); - expect(metadata).toEqual(validMetadata); - - // Verify both calls were made - expect(mockFetch).toHaveBeenCalledTimes(2); - - // Verify first call had MCP header - expect(mockFetch.mock.calls[0][1]?.headers).toHaveProperty('MCP-Protocol-Version'); - }); - - it('throws an error when all fetch attempts fail', async () => { - // Set up a counter to control behavior - let callCount = 0; - - // Mock implementation that changes behavior based on call count - mockFetch.mockImplementation((_url, _options) => { - callCount++; - - if (callCount === 1) { - // First call - fail with TypeError - return Promise.reject(new TypeError('First failure')); - } else { - // Second call - fail with different error - return Promise.reject(new Error('Second failure')); - } - }); - - // Should fail with the second error - await expect(discoverOAuthProtectedResourceMetadata('https://resource.example.com')).rejects.toThrow('Second failure'); - - // Verify both calls were made - expect(mockFetch).toHaveBeenCalledTimes(2); - }); - - it('throws on 404 errors', async () => { - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - await expect(discoverOAuthProtectedResourceMetadata('https://resource.example.com')).rejects.toThrow( - 'Resource server does not implement OAuth 2.0 Protected Resource Metadata.' - ); - }); - - it('throws on non-404 errors', async () => { - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 500 - }); - - await expect(discoverOAuthProtectedResourceMetadata('https://resource.example.com')).rejects.toThrow('HTTP 500'); - }); - - it('validates metadata schema', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - // Missing required fields - scopes_supported: ['email', 'mcp'] - }) - }); - - await expect(discoverOAuthProtectedResourceMetadata('https://resource.example.com')).rejects.toThrow(); - }); - - it('returns metadata when discovery succeeds with path', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthProtectedResourceMetadata('https://resource.example.com/path/name'); - expect(metadata).toEqual(validMetadata); - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); - const [url] = calls[0]; - expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource/path/name'); - }); - - it('preserves query parameters in path-aware discovery', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthProtectedResourceMetadata('https://resource.example.com/path?param=value'); - expect(metadata).toEqual(validMetadata); - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); - const [url] = calls[0]; - expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource/path?param=value'); - }); - - it.each([400, 401, 403, 404, 410, 422, 429])( - 'falls back to root discovery when path-aware discovery returns %d', - async statusCode => { - // First call (path-aware) returns 4xx - mockFetch.mockResolvedValueOnce({ - ok: false, - status: statusCode - }); - - // Second call (root fallback) succeeds - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthProtectedResourceMetadata('https://resource.example.com/path/name'); - expect(metadata).toEqual(validMetadata); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(2); - - // First call should be path-aware - const [firstUrl, firstOptions] = calls[0]; - expect(firstUrl.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource/path/name'); - expect(firstOptions.headers).toEqual({ - 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION - }); - - // Second call should be root fallback - const [secondUrl, secondOptions] = calls[1]; - expect(secondUrl.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); - expect(secondOptions.headers).toEqual({ - 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION - }); - } - ); - - it('throws error when both path-aware and root discovery return 404', async () => { - // First call (path-aware) returns 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - // Second call (root fallback) also returns 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - await expect(discoverOAuthProtectedResourceMetadata('https://resource.example.com/path/name')).rejects.toThrow( - 'Resource server does not implement OAuth 2.0 Protected Resource Metadata.' - ); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(2); - }); - - it('throws error on 500 status and does not fallback', async () => { - // First call (path-aware) returns 500 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 500 - }); - - await expect(discoverOAuthProtectedResourceMetadata('https://resource.example.com/path/name')).rejects.toThrow(); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); // Should not attempt fallback - }); - - it('does not fallback when the original URL is already at root path', async () => { - // First call (path-aware for root) returns 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - await expect(discoverOAuthProtectedResourceMetadata('https://resource.example.com/')).rejects.toThrow( - 'Resource server does not implement OAuth 2.0 Protected Resource Metadata.' - ); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); // Should not attempt fallback - - const [url] = calls[0]; - expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); - }); - - it('does not fallback when the original URL has no path', async () => { - // First call (path-aware for no path) returns 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - await expect(discoverOAuthProtectedResourceMetadata('https://resource.example.com')).rejects.toThrow( - 'Resource server does not implement OAuth 2.0 Protected Resource Metadata.' - ); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); // Should not attempt fallback - - const [url] = calls[0]; - expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); - }); - - it('falls back when path-aware discovery encounters CORS error', async () => { - // First call (path-aware) fails with TypeError (CORS) - mockFetch.mockImplementationOnce(() => Promise.reject(new TypeError('CORS error'))); - - // Retry path-aware without headers (simulating CORS retry) - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - // Second call (root fallback) succeeds - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthProtectedResourceMetadata('https://resource.example.com/deep/path'); - expect(metadata).toEqual(validMetadata); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(3); - - // Final call should be root fallback - const [lastUrl, lastOptions] = calls[2]; - expect(lastUrl.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); - expect(lastOptions.headers).toEqual({ - 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION - }); - }); - - it('does not fallback when resourceMetadataUrl is provided', async () => { - // Call with explicit URL returns 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - await expect( - discoverOAuthProtectedResourceMetadata('https://resource.example.com/path', { - resourceMetadataUrl: 'https://custom.example.com/metadata' - }) - ).rejects.toThrow('Resource server does not implement OAuth 2.0 Protected Resource Metadata.'); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); // Should not attempt fallback when explicit URL is provided - - const [url] = calls[0]; - expect(url.toString()).toBe('https://custom.example.com/metadata'); - }); - - it('supports overriding the fetch function used for requests', async () => { - const validMetadata = { - resource: 'https://resource.example.com', - authorization_servers: ['https://auth.example.com'] - }; - - const customFetch = jest.fn().mockResolvedValue({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthProtectedResourceMetadata('https://resource.example.com', undefined, customFetch); - - expect(metadata).toEqual(validMetadata); - expect(customFetch).toHaveBeenCalledTimes(1); - expect(mockFetch).not.toHaveBeenCalled(); - - const [url, options] = customFetch.mock.calls[0]; - expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); - expect(options.headers).toEqual({ - 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION - }); - }); - }); - - describe('discoverOAuthMetadata', () => { - const validMetadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - registration_endpoint: 'https://auth.example.com/register', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }; - - it('returns metadata when discovery succeeds', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthMetadata('https://auth.example.com'); - expect(metadata).toEqual(validMetadata); - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); - const [url, options] = calls[0]; - expect(url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); - expect(options.headers).toEqual({ - 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION - }); - }); - - it('returns metadata when discovery succeeds with path', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthMetadata('https://auth.example.com/path/name'); - expect(metadata).toEqual(validMetadata); - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); - const [url, options] = calls[0]; - expect(url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/path/name'); - expect(options.headers).toEqual({ - 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION - }); - }); - - it('falls back to root discovery when path-aware discovery returns 404', async () => { - // First call (path-aware) returns 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - // Second call (root fallback) succeeds - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthMetadata('https://auth.example.com/path/name'); - expect(metadata).toEqual(validMetadata); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(2); - - // First call should be path-aware - const [firstUrl, firstOptions] = calls[0]; - expect(firstUrl.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/path/name'); - expect(firstOptions.headers).toEqual({ - 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION - }); - - // Second call should be root fallback - const [secondUrl, secondOptions] = calls[1]; - expect(secondUrl.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); - expect(secondOptions.headers).toEqual({ - 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION - }); - }); - - it('returns undefined when both path-aware and root discovery return 404', async () => { - // First call (path-aware) returns 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - // Second call (root fallback) also returns 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - const metadata = await discoverOAuthMetadata('https://auth.example.com/path/name'); - expect(metadata).toBeUndefined(); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(2); - }); - - it('does not fallback when the original URL is already at root path', async () => { - // First call (path-aware for root) returns 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - const metadata = await discoverOAuthMetadata('https://auth.example.com/'); - expect(metadata).toBeUndefined(); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); // Should not attempt fallback - - const [url] = calls[0]; - expect(url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); - }); - - it('does not fallback when the original URL has no path', async () => { - // First call (path-aware for no path) returns 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - const metadata = await discoverOAuthMetadata('https://auth.example.com'); - expect(metadata).toBeUndefined(); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(1); // Should not attempt fallback - - const [url] = calls[0]; - expect(url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); - }); - - it('falls back when path-aware discovery encounters CORS error', async () => { - // First call (path-aware) fails with TypeError (CORS) - mockFetch.mockImplementationOnce(() => Promise.reject(new TypeError('CORS error'))); - - // Retry path-aware without headers (simulating CORS retry) - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - // Second call (root fallback) succeeds - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthMetadata('https://auth.example.com/deep/path'); - expect(metadata).toEqual(validMetadata); - - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(3); - - // Final call should be root fallback - const [lastUrl, lastOptions] = calls[2]; - expect(lastUrl.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); - expect(lastOptions.headers).toEqual({ - 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION - }); - }); - - it('returns metadata when first fetch fails but second without MCP header succeeds', async () => { - // Set up a counter to control behavior - let callCount = 0; - - // Mock implementation that changes behavior based on call count - mockFetch.mockImplementation((_url, _options) => { - callCount++; - - if (callCount === 1) { - // First call with MCP header - fail with TypeError (simulating CORS error) - // We need to use TypeError specifically because that's what the implementation checks for - return Promise.reject(new TypeError('Network error')); - } else { - // Second call without header - succeed - return Promise.resolve({ - ok: true, - status: 200, - json: async () => validMetadata - }); - } - }); - - // Should succeed with the second call - const metadata = await discoverOAuthMetadata('https://auth.example.com'); - expect(metadata).toEqual(validMetadata); - - // Verify both calls were made - expect(mockFetch).toHaveBeenCalledTimes(2); - - // Verify first call had MCP header - expect(mockFetch.mock.calls[0][1]?.headers).toHaveProperty('MCP-Protocol-Version'); - }); - - it('throws an error when all fetch attempts fail', async () => { - // Set up a counter to control behavior - let callCount = 0; - - // Mock implementation that changes behavior based on call count - mockFetch.mockImplementation((_url, _options) => { - callCount++; - - if (callCount === 1) { - // First call - fail with TypeError - return Promise.reject(new TypeError('First failure')); - } else { - // Second call - fail with different error - return Promise.reject(new Error('Second failure')); - } - }); - - // Should fail with the second error - await expect(discoverOAuthMetadata('https://auth.example.com')).rejects.toThrow('Second failure'); - - // Verify both calls were made - expect(mockFetch).toHaveBeenCalledTimes(2); - }); - - it('returns undefined when both CORS requests fail in fetchWithCorsRetry', async () => { - // fetchWithCorsRetry tries with headers (fails with CORS), then retries without headers (also fails with CORS) - // simulating a 404 w/o headers set. We want this to return undefined, not throw TypeError - mockFetch.mockImplementation(() => { - // Both the initial request with headers and retry without headers fail with CORS TypeError - return Promise.reject(new TypeError('Failed to fetch')); - }); - - // This should return undefined (the desired behavior after the fix) - const metadata = await discoverOAuthMetadata('https://auth.example.com/path'); - expect(metadata).toBeUndefined(); - }); - - it('returns undefined when discovery endpoint returns 404', async () => { - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - const metadata = await discoverOAuthMetadata('https://auth.example.com'); - expect(metadata).toBeUndefined(); - }); - - it('throws on non-404 errors', async () => { - mockFetch.mockResolvedValueOnce(new Response(null, { status: 500 })); - - await expect(discoverOAuthMetadata('https://auth.example.com')).rejects.toThrow('HTTP 500'); - }); - - it('validates metadata schema', async () => { - mockFetch.mockResolvedValueOnce( - Response.json( - { - // Missing required fields - issuer: 'https://auth.example.com' - }, - { status: 200 } - ) - ); - - await expect(discoverOAuthMetadata('https://auth.example.com')).rejects.toThrow(); - }); - - it('supports overriding the fetch function used for requests', async () => { - const validMetadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - registration_endpoint: 'https://auth.example.com/register', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }; - - const customFetch = jest.fn().mockResolvedValue({ - ok: true, - status: 200, - json: async () => validMetadata - }); - - const metadata = await discoverOAuthMetadata('https://auth.example.com', {}, customFetch); - - expect(metadata).toEqual(validMetadata); - expect(customFetch).toHaveBeenCalledTimes(1); - expect(mockFetch).not.toHaveBeenCalled(); - - const [url, options] = customFetch.mock.calls[0]; - expect(url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); - expect(options.headers).toEqual({ - 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION - }); - }); - }); - - describe('buildDiscoveryUrls', () => { - it('generates correct URLs for server without path', () => { - const urls = buildDiscoveryUrls('https://auth.example.com'); - - expect(urls).toHaveLength(2); - expect(urls.map(u => ({ url: u.url.toString(), type: u.type }))).toEqual([ - { - url: 'https://auth.example.com/.well-known/oauth-authorization-server', - type: 'oauth' - }, - { - url: 'https://auth.example.com/.well-known/openid-configuration', - type: 'oidc' - } - ]); - }); - - it('generates correct URLs for server with path', () => { - const urls = buildDiscoveryUrls('https://auth.example.com/tenant1'); - - expect(urls).toHaveLength(4); - expect(urls.map(u => ({ url: u.url.toString(), type: u.type }))).toEqual([ - { - url: 'https://auth.example.com/.well-known/oauth-authorization-server/tenant1', - type: 'oauth' - }, - { - url: 'https://auth.example.com/.well-known/oauth-authorization-server', - type: 'oauth' - }, - { - url: 'https://auth.example.com/.well-known/openid-configuration/tenant1', - type: 'oidc' - }, - { - url: 'https://auth.example.com/tenant1/.well-known/openid-configuration', - type: 'oidc' - } - ]); - }); - - it('handles URL object input', () => { - const urls = buildDiscoveryUrls(new URL('https://auth.example.com/tenant1')); - - expect(urls).toHaveLength(4); - expect(urls[0].url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/tenant1'); - }); - }); - - describe('discoverAuthorizationServerMetadata', () => { - const validOAuthMetadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - registration_endpoint: 'https://auth.example.com/register', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }; - - const validOpenIdMetadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - jwks_uri: 'https://auth.example.com/jwks', - subject_types_supported: ['public'], - id_token_signing_alg_values_supported: ['RS256'], - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }; - - it('tries URLs in order and returns first successful metadata', async () => { - // First OAuth URL fails with 404 - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 404 - }); - - // Second OAuth URL (root) succeeds - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validOAuthMetadata - }); - - const metadata = await discoverAuthorizationServerMetadata('https://auth.example.com/tenant1'); - - expect(metadata).toEqual(validOAuthMetadata); - - // Verify it tried the URLs in the correct order - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(2); - expect(calls[0][0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/tenant1'); - expect(calls[1][0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); - }); - - it('continues on 4xx errors', async () => { - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 400 - }); - - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validOpenIdMetadata - }); - - const metadata = await discoverAuthorizationServerMetadata('https://mcp.example.com'); - - expect(metadata).toEqual(validOpenIdMetadata); - }); - - it('throws on non-4xx errors', async () => { - mockFetch.mockResolvedValueOnce({ - ok: false, - status: 500 - }); - - await expect(discoverAuthorizationServerMetadata('https://mcp.example.com')).rejects.toThrow('HTTP 500'); - }); - - it('handles CORS errors with retry', async () => { - // First call fails with CORS - mockFetch.mockImplementationOnce(() => Promise.reject(new TypeError('CORS error'))); - - // Retry without headers succeeds - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validOAuthMetadata - }); - - const metadata = await discoverAuthorizationServerMetadata('https://auth.example.com'); - - expect(metadata).toEqual(validOAuthMetadata); - const calls = mockFetch.mock.calls; - expect(calls.length).toBe(2); - - // First call should have headers - expect(calls[0][1]?.headers).toHaveProperty('MCP-Protocol-Version'); - - // Second call should not have headers (CORS retry) - expect(calls[1][1]?.headers).toBeUndefined(); - }); - - it('supports custom fetch function', async () => { - const customFetch = jest.fn().mockResolvedValue({ - ok: true, - status: 200, - json: async () => validOAuthMetadata - }); - - const metadata = await discoverAuthorizationServerMetadata('https://auth.example.com', { fetchFn: customFetch }); - - expect(metadata).toEqual(validOAuthMetadata); - expect(customFetch).toHaveBeenCalledTimes(1); - expect(mockFetch).not.toHaveBeenCalled(); - }); - - it('supports custom protocol version', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validOAuthMetadata - }); - - const metadata = await discoverAuthorizationServerMetadata('https://auth.example.com', { protocolVersion: '2025-01-01' }); - - expect(metadata).toEqual(validOAuthMetadata); - const calls = mockFetch.mock.calls; - const [, options] = calls[0]; - expect(options.headers).toEqual({ - 'MCP-Protocol-Version': '2025-01-01', - Accept: 'application/json' - }); - }); - - it('returns undefined when all URLs fail with CORS errors', async () => { - // All fetch attempts fail with CORS errors (TypeError) - mockFetch.mockImplementation(() => Promise.reject(new TypeError('CORS error'))); - - const metadata = await discoverAuthorizationServerMetadata('https://auth.example.com/tenant1'); - - expect(metadata).toBeUndefined(); - - // Verify that all discovery URLs were attempted - expect(mockFetch).toHaveBeenCalledTimes(8); // 4 URLs × 2 attempts each (with and without headers) - }); - }); - - describe('startAuthorization', () => { - const validMetadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/auth', - token_endpoint: 'https://auth.example.com/tkn', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }; - - const validOpenIdMetadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/auth', - token_endpoint: 'https://auth.example.com/token', - jwks_uri: 'https://auth.example.com/jwks', - subject_types_supported: ['public'], - id_token_signing_alg_values_supported: ['RS256'], - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }; - - const validClientInfo = { - client_id: 'client123', - client_secret: 'secret123', - redirect_uris: ['http://localhost:3000/callback'], - client_name: 'Test Client' - }; - - it('generates authorization URL with PKCE challenge', async () => { - const { authorizationUrl, codeVerifier } = await startAuthorization('https://auth.example.com', { - metadata: undefined, - clientInformation: validClientInfo, - redirectUrl: 'http://localhost:3000/callback', - resource: new URL('https://api.example.com/mcp-server') - }); - - expect(authorizationUrl.toString()).toMatch(/^https:\/\/auth\.example\.com\/authorize\?/); - expect(authorizationUrl.searchParams.get('response_type')).toBe('code'); - expect(authorizationUrl.searchParams.get('code_challenge')).toBe('test_challenge'); - expect(authorizationUrl.searchParams.get('code_challenge_method')).toBe('S256'); - expect(authorizationUrl.searchParams.get('redirect_uri')).toBe('http://localhost:3000/callback'); - expect(authorizationUrl.searchParams.get('resource')).toBe('https://api.example.com/mcp-server'); - expect(codeVerifier).toBe('test_verifier'); - }); - - it('includes scope parameter when provided', async () => { - const { authorizationUrl } = await startAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - redirectUrl: 'http://localhost:3000/callback', - scope: 'read write profile' - }); - - expect(authorizationUrl.searchParams.get('scope')).toBe('read write profile'); - }); - - it('excludes scope parameter when not provided', async () => { - const { authorizationUrl } = await startAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - redirectUrl: 'http://localhost:3000/callback' - }); - - expect(authorizationUrl.searchParams.has('scope')).toBe(false); - }); - - it('includes state parameter when provided', async () => { - const { authorizationUrl } = await startAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - redirectUrl: 'http://localhost:3000/callback', - state: 'foobar' - }); - - expect(authorizationUrl.searchParams.get('state')).toBe('foobar'); - }); - - it('excludes state parameter when not provided', async () => { - const { authorizationUrl } = await startAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - redirectUrl: 'http://localhost:3000/callback' - }); - - expect(authorizationUrl.searchParams.has('state')).toBe(false); - }); - - // OpenID Connect requires that the user is prompted for consent if the scope includes 'offline_access' - it("includes consent prompt parameter if scope includes 'offline_access'", async () => { - const { authorizationUrl } = await startAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - redirectUrl: 'http://localhost:3000/callback', - scope: 'read write profile offline_access' - }); - - expect(authorizationUrl.searchParams.get('prompt')).toBe('consent'); - }); - - it.each([validMetadata, validOpenIdMetadata])('uses metadata authorization_endpoint when provided', async baseMetadata => { - const { authorizationUrl } = await startAuthorization('https://auth.example.com', { - metadata: baseMetadata, - clientInformation: validClientInfo, - redirectUrl: 'http://localhost:3000/callback' - }); - - expect(authorizationUrl.toString()).toMatch(/^https:\/\/auth\.example\.com\/auth\?/); - }); - - it.each([validMetadata, validOpenIdMetadata])('validates response type support', async baseMetadata => { - const metadata = { - ...baseMetadata, - response_types_supported: ['token'] // Does not support 'code' - }; - - await expect( - startAuthorization('https://auth.example.com', { - metadata, - clientInformation: validClientInfo, - redirectUrl: 'http://localhost:3000/callback' - }) - ).rejects.toThrow(/does not support response type/); - }); - - // https://github.com/modelcontextprotocol/typescript-sdk/issues/832 - it.each([validMetadata, validOpenIdMetadata])( - 'assumes supported code challenge methods includes S256 if absent', - async baseMetadata => { - const metadata = { - ...baseMetadata, - response_types_supported: ['code'], - code_challenge_methods_supported: undefined - }; - - const { authorizationUrl } = await startAuthorization('https://auth.example.com', { - metadata, - clientInformation: validClientInfo, - redirectUrl: 'http://localhost:3000/callback' - }); - - expect(authorizationUrl.toString()).toMatch(/^https:\/\/auth\.example\.com\/auth\?.+&code_challenge_method=S256/); - } - ); - - it.each([validMetadata, validOpenIdMetadata])( - 'validates supported code challenge methods includes S256 if present', - async baseMetadata => { - const metadata = { - ...baseMetadata, - response_types_supported: ['code'], - code_challenge_methods_supported: ['plain'] // Does not support 'S256' - }; - - await expect( - startAuthorization('https://auth.example.com', { - metadata, - clientInformation: validClientInfo, - redirectUrl: 'http://localhost:3000/callback' - }) - ).rejects.toThrow(/does not support code challenge method/); - } - ); - }); - - describe('exchangeAuthorization', () => { - const validTokens = { - access_token: 'access123', - token_type: 'Bearer', - expires_in: 3600, - refresh_token: 'refresh123' - }; - - const validMetadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'] - }; - - const validClientInfo = { - client_id: 'client123', - client_secret: 'secret123', - redirect_uris: ['http://localhost:3000/callback'], - client_name: 'Test Client' - }; - - it('exchanges code for tokens', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const tokens = await exchangeAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - authorizationCode: 'code123', - codeVerifier: 'verifier123', - redirectUri: 'http://localhost:3000/callback', - resource: new URL('https://api.example.com/mcp-server') - }); - - expect(tokens).toEqual(validTokens); - expect(mockFetch).toHaveBeenCalledWith( - expect.objectContaining({ - href: 'https://auth.example.com/token' - }), - expect.objectContaining({ - method: 'POST', - headers: new Headers({ - 'Content-Type': 'application/x-www-form-urlencoded' - }) - }) - ); - - const body = mockFetch.mock.calls[0][1].body as URLSearchParams; - expect(body.get('grant_type')).toBe('authorization_code'); - expect(body.get('code')).toBe('code123'); - expect(body.get('code_verifier')).toBe('verifier123'); - expect(body.get('client_id')).toBe('client123'); - expect(body.get('client_secret')).toBe('secret123'); - expect(body.get('redirect_uri')).toBe('http://localhost:3000/callback'); - expect(body.get('resource')).toBe('https://api.example.com/mcp-server'); - }); - - it('exchanges code for tokens with auth', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const tokens = await exchangeAuthorization('https://auth.example.com', { - metadata: validMetadata, - clientInformation: validClientInfo, - authorizationCode: 'code123', - codeVerifier: 'verifier123', - redirectUri: 'http://localhost:3000/callback', - addClientAuthentication: ( - headers: Headers, - params: URLSearchParams, - url: string | URL, - metadata: AuthorizationServerMetadata - ) => { - headers.set('Authorization', 'Basic ' + btoa(validClientInfo.client_id + ':' + validClientInfo.client_secret)); - params.set('example_url', typeof url === 'string' ? url : url.toString()); - params.set('example_metadata', metadata.authorization_endpoint); - params.set('example_param', 'example_value'); - } - }); - - expect(tokens).toEqual(validTokens); - expect(mockFetch).toHaveBeenCalledWith( - expect.objectContaining({ - href: 'https://auth.example.com/token' - }), - expect.objectContaining({ - method: 'POST' - }) - ); - - const headers = mockFetch.mock.calls[0][1].headers as Headers; - expect(headers.get('Content-Type')).toBe('application/x-www-form-urlencoded'); - expect(headers.get('Authorization')).toBe('Basic Y2xpZW50MTIzOnNlY3JldDEyMw=='); - const body = mockFetch.mock.calls[0][1].body as URLSearchParams; - expect(body.get('grant_type')).toBe('authorization_code'); - expect(body.get('code')).toBe('code123'); - expect(body.get('code_verifier')).toBe('verifier123'); - expect(body.get('client_id')).toBeNull(); - expect(body.get('redirect_uri')).toBe('http://localhost:3000/callback'); - expect(body.get('example_url')).toBe('https://auth.example.com'); - expect(body.get('example_metadata')).toBe('https://auth.example.com/authorize'); - expect(body.get('example_param')).toBe('example_value'); - expect(body.get('client_secret')).toBeNull(); - }); - - it('validates token response schema', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - // Missing required fields - access_token: 'access123' - }) - }); - - await expect( - exchangeAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - authorizationCode: 'code123', - codeVerifier: 'verifier123', - redirectUri: 'http://localhost:3000/callback' - }) - ).rejects.toThrow(); - }); - - it('throws on error response', async () => { - mockFetch.mockResolvedValueOnce(Response.json(new ServerError('Token exchange failed').toResponseObject(), { status: 400 })); - - await expect( - exchangeAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - authorizationCode: 'code123', - codeVerifier: 'verifier123', - redirectUri: 'http://localhost:3000/callback' - }) - ).rejects.toThrow('Token exchange failed'); - }); - - it('supports overriding the fetch function used for requests', async () => { - const customFetch = jest.fn().mockResolvedValue({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const tokens = await exchangeAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - authorizationCode: 'code123', - codeVerifier: 'verifier123', - redirectUri: 'http://localhost:3000/callback', - resource: new URL('https://api.example.com/mcp-server'), - fetchFn: customFetch - }); - - expect(tokens).toEqual(validTokens); - expect(customFetch).toHaveBeenCalledTimes(1); - expect(mockFetch).not.toHaveBeenCalled(); - - const [url, options] = customFetch.mock.calls[0]; - expect(url.toString()).toBe('https://auth.example.com/token'); - expect(options).toEqual( - expect.objectContaining({ - method: 'POST', - headers: expect.any(Headers), - body: expect.any(URLSearchParams) - }) - ); - - const body = options.body as URLSearchParams; - expect(body.get('grant_type')).toBe('authorization_code'); - expect(body.get('code')).toBe('code123'); - expect(body.get('code_verifier')).toBe('verifier123'); - expect(body.get('client_id')).toBe('client123'); - expect(body.get('client_secret')).toBe('secret123'); - expect(body.get('redirect_uri')).toBe('http://localhost:3000/callback'); - expect(body.get('resource')).toBe('https://api.example.com/mcp-server'); - }); - }); - - describe('refreshAuthorization', () => { - const validTokens = { - access_token: 'newaccess123', - token_type: 'Bearer', - expires_in: 3600 - }; - const validTokensWithNewRefreshToken = { - ...validTokens, - refresh_token: 'newrefresh123' - }; - - const validMetadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'] - }; - - const validClientInfo = { - client_id: 'client123', - client_secret: 'secret123', - redirect_uris: ['http://localhost:3000/callback'], - client_name: 'Test Client' - }; - - it('exchanges refresh token for new tokens', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokensWithNewRefreshToken - }); - - const tokens = await refreshAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - refreshToken: 'refresh123', - resource: new URL('https://api.example.com/mcp-server') - }); - - expect(tokens).toEqual(validTokensWithNewRefreshToken); - expect(mockFetch).toHaveBeenCalledWith( - expect.objectContaining({ - href: 'https://auth.example.com/token' - }), - expect.objectContaining({ - method: 'POST', - headers: new Headers({ - 'Content-Type': 'application/x-www-form-urlencoded' - }) - }) - ); - - const body = mockFetch.mock.calls[0][1].body as URLSearchParams; - expect(body.get('grant_type')).toBe('refresh_token'); - expect(body.get('refresh_token')).toBe('refresh123'); - expect(body.get('client_id')).toBe('client123'); - expect(body.get('client_secret')).toBe('secret123'); - expect(body.get('resource')).toBe('https://api.example.com/mcp-server'); - }); - - it('exchanges refresh token for new tokens with auth', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokensWithNewRefreshToken - }); - - const tokens = await refreshAuthorization('https://auth.example.com', { - metadata: validMetadata, - clientInformation: validClientInfo, - refreshToken: 'refresh123', - addClientAuthentication: ( - headers: Headers, - params: URLSearchParams, - url: string | URL, - metadata?: AuthorizationServerMetadata - ) => { - headers.set('Authorization', 'Basic ' + btoa(validClientInfo.client_id + ':' + validClientInfo.client_secret)); - params.set('example_url', typeof url === 'string' ? url : url.toString()); - params.set('example_metadata', metadata?.authorization_endpoint ?? '?'); - params.set('example_param', 'example_value'); - } - }); - - expect(tokens).toEqual(validTokensWithNewRefreshToken); - expect(mockFetch).toHaveBeenCalledWith( - expect.objectContaining({ - href: 'https://auth.example.com/token' - }), - expect.objectContaining({ - method: 'POST' - }) - ); - - const headers = mockFetch.mock.calls[0][1].headers as Headers; - expect(headers.get('Content-Type')).toBe('application/x-www-form-urlencoded'); - expect(headers.get('Authorization')).toBe('Basic Y2xpZW50MTIzOnNlY3JldDEyMw=='); - const body = mockFetch.mock.calls[0][1].body as URLSearchParams; - expect(body.get('grant_type')).toBe('refresh_token'); - expect(body.get('refresh_token')).toBe('refresh123'); - expect(body.get('client_id')).toBeNull(); - expect(body.get('example_url')).toBe('https://auth.example.com'); - expect(body.get('example_metadata')).toBe('https://auth.example.com/authorize'); - expect(body.get('example_param')).toBe('example_value'); - expect(body.get('client_secret')).toBeNull(); - }); - - it('exchanges refresh token for new tokens and keep existing refresh token if none is returned', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const refreshToken = 'refresh123'; - const tokens = await refreshAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - refreshToken - }); - - expect(tokens).toEqual({ refresh_token: refreshToken, ...validTokens }); - }); - - it('validates token response schema', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - // Missing required fields - access_token: 'newaccess123' - }) - }); - - await expect( - refreshAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - refreshToken: 'refresh123' - }) - ).rejects.toThrow(); - }); - - it('throws on error response', async () => { - mockFetch.mockResolvedValueOnce(Response.json(new ServerError('Token refresh failed').toResponseObject(), { status: 400 })); - - await expect( - refreshAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - refreshToken: 'refresh123' - }) - ).rejects.toThrow('Token refresh failed'); - }); - }); - - describe('registerClient', () => { - const validClientMetadata = { - redirect_uris: ['http://localhost:3000/callback'], - client_name: 'Test Client' - }; - - const validClientInfo = { - client_id: 'client123', - client_secret: 'secret123', - client_id_issued_at: 1612137600, - client_secret_expires_at: 1612224000, - ...validClientMetadata - }; - - it('registers client and returns client information', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validClientInfo - }); - - const clientInfo = await registerClient('https://auth.example.com', { - clientMetadata: validClientMetadata - }); - - expect(clientInfo).toEqual(validClientInfo); - expect(mockFetch).toHaveBeenCalledWith( - expect.objectContaining({ - href: 'https://auth.example.com/register' - }), - expect.objectContaining({ - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(validClientMetadata) - }) - ); - }); - - it('validates client information response schema', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - // Missing required fields - client_secret: 'secret123' - }) - }); - - await expect( - registerClient('https://auth.example.com', { - clientMetadata: validClientMetadata - }) - ).rejects.toThrow(); - }); - - it('throws when registration endpoint not available in metadata', async () => { - const metadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'] - }; - - await expect( - registerClient('https://auth.example.com', { - metadata, - clientMetadata: validClientMetadata - }) - ).rejects.toThrow(/does not support dynamic client registration/); - }); - - it('throws on error response', async () => { - mockFetch.mockResolvedValueOnce( - Response.json(new ServerError('Dynamic client registration failed').toResponseObject(), { status: 400 }) - ); - - await expect( - registerClient('https://auth.example.com', { - clientMetadata: validClientMetadata - }) - ).rejects.toThrow('Dynamic client registration failed'); - }); - }); - - describe('auth function', () => { - const mockProvider: OAuthClientProvider = { - get redirectUrl() { - return 'http://localhost:3000/callback'; - }, - get clientMetadata() { - return { - redirect_uris: ['http://localhost:3000/callback'], - client_name: 'Test Client' - }; - }, - clientInformation: jest.fn(), - tokens: jest.fn(), - saveTokens: jest.fn(), - redirectToAuthorization: jest.fn(), - saveCodeVerifier: jest.fn(), - codeVerifier: jest.fn() - }; - - beforeEach(() => { - jest.clearAllMocks(); - }); - - it('falls back to /.well-known/oauth-authorization-server when no protected-resource-metadata', async () => { - // Setup: First call to protected resource metadata fails (404) - // Second call to auth server metadata succeeds - let callCount = 0; - mockFetch.mockImplementation(url => { - callCount++; - - const urlString = url.toString(); - - if (callCount === 1 && urlString.includes('/.well-known/oauth-protected-resource')) { - // First call - protected resource metadata fails with 404 - return Promise.resolve({ - ok: false, - status: 404 - }); - } else if (callCount === 2 && urlString.includes('/.well-known/oauth-authorization-server')) { - // Second call - auth server metadata succeeds - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - registration_endpoint: 'https://auth.example.com/register', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - } else if (callCount === 3 && urlString.includes('/register')) { - // Third call - client registration succeeds - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - client_id: 'test-client-id', - client_secret: 'test-client-secret', - client_id_issued_at: 1612137600, - client_secret_expires_at: 1612224000, - redirect_uris: ['http://localhost:3000/callback'], - client_name: 'Test Client' - }) - }); - } - - return Promise.reject(new Error(`Unexpected fetch call: ${urlString}`)); - }); - - // Mock provider methods - (mockProvider.clientInformation as jest.Mock).mockResolvedValue(undefined); - (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); - mockProvider.saveClientInformation = jest.fn(); - - // Call the auth function - const result = await auth(mockProvider, { - serverUrl: 'https://resource.example.com' - }); - - // Verify the result - expect(result).toBe('REDIRECT'); - - // Verify the sequence of calls - expect(mockFetch).toHaveBeenCalledTimes(3); - - // First call should be to protected resource metadata - expect(mockFetch.mock.calls[0][0].toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); - - // Second call should be to oauth metadata - expect(mockFetch.mock.calls[1][0].toString()).toBe('https://resource.example.com/.well-known/oauth-authorization-server'); - }); - - it('passes resource parameter through authorization flow', async () => { - // Mock successful metadata discovery - need to include protected resource metadata - mockFetch.mockImplementation(url => { - const urlString = url.toString(); - if (urlString.includes('/.well-known/oauth-protected-resource')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - resource: 'https://api.example.com/mcp-server', - authorization_servers: ['https://auth.example.com'] - }) - }); - } else if (urlString.includes('/.well-known/oauth-authorization-server')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - } - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods for authorization flow - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: 'test-client', - client_secret: 'test-secret' - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); - (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); - (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - - // Call auth without authorization code (should trigger redirect) - const result = await auth(mockProvider, { - serverUrl: 'https://api.example.com/mcp-server' - }); - - expect(result).toBe('REDIRECT'); - - // Verify the authorization URL includes the resource parameter - expect(mockProvider.redirectToAuthorization).toHaveBeenCalledWith( - expect.objectContaining({ - searchParams: expect.any(URLSearchParams) - }) - ); - - const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; - const authUrl: URL = redirectCall[0]; - expect(authUrl.searchParams.get('resource')).toBe('https://api.example.com/mcp-server'); - }); - - it('includes resource in token exchange when authorization code is provided', async () => { - // Mock successful metadata discovery and token exchange - need protected resource metadata - mockFetch.mockImplementation(url => { - const urlString = url.toString(); - - if (urlString.includes('/.well-known/oauth-protected-resource')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - resource: 'https://api.example.com/mcp-server', - authorization_servers: ['https://auth.example.com'] - }) - }); - } else if (urlString.includes('/.well-known/oauth-authorization-server')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - } else if (urlString.includes('/token')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - access_token: 'access123', - token_type: 'Bearer', - expires_in: 3600, - refresh_token: 'refresh123' - }) - }); - } - - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods for token exchange - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: 'test-client', - client_secret: 'test-secret' - }); - (mockProvider.codeVerifier as jest.Mock).mockResolvedValue('test-verifier'); - (mockProvider.saveTokens as jest.Mock).mockResolvedValue(undefined); - - // Call auth with authorization code - const result = await auth(mockProvider, { - serverUrl: 'https://api.example.com/mcp-server', - authorizationCode: 'auth-code-123' - }); - - expect(result).toBe('AUTHORIZED'); - - // Find the token exchange call - const tokenCall = mockFetch.mock.calls.find(call => call[0].toString().includes('/token')); - expect(tokenCall).toBeDefined(); - - const body = tokenCall![1].body as URLSearchParams; - expect(body.get('resource')).toBe('https://api.example.com/mcp-server'); - expect(body.get('code')).toBe('auth-code-123'); - }); - - it('includes resource in token refresh', async () => { - // Mock successful metadata discovery and token refresh - need protected resource metadata - mockFetch.mockImplementation(url => { - const urlString = url.toString(); - - if (urlString.includes('/.well-known/oauth-protected-resource')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - resource: 'https://api.example.com/mcp-server', - authorization_servers: ['https://auth.example.com'] - }) - }); - } else if (urlString.includes('/.well-known/oauth-authorization-server')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - } else if (urlString.includes('/token')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - access_token: 'new-access123', - token_type: 'Bearer', - expires_in: 3600 - }) - }); - } - - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods for token refresh - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: 'test-client', - client_secret: 'test-secret' - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue({ - access_token: 'old-access', - refresh_token: 'refresh123' - }); - (mockProvider.saveTokens as jest.Mock).mockResolvedValue(undefined); - - // Call auth with existing tokens (should trigger refresh) - const result = await auth(mockProvider, { - serverUrl: 'https://api.example.com/mcp-server' - }); - - expect(result).toBe('AUTHORIZED'); - - // Find the token refresh call - const tokenCall = mockFetch.mock.calls.find(call => call[0].toString().includes('/token')); - expect(tokenCall).toBeDefined(); - - const body = tokenCall![1].body as URLSearchParams; - expect(body.get('resource')).toBe('https://api.example.com/mcp-server'); - expect(body.get('grant_type')).toBe('refresh_token'); - expect(body.get('refresh_token')).toBe('refresh123'); - }); - - it('skips default PRM resource validation when custom validateResourceURL is provided', async () => { - const mockValidateResourceURL = jest.fn().mockResolvedValue(undefined); - const providerWithCustomValidation = { - ...mockProvider, - validateResourceURL: mockValidateResourceURL - }; - - // Mock protected resource metadata with mismatched resource URL - // This would normally throw an error in default validation, but should be skipped - mockFetch.mockImplementation(url => { - const urlString = url.toString(); - - if (urlString.includes('/.well-known/oauth-protected-resource')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - resource: 'https://different-resource.example.com/mcp-server', // Mismatched resource - authorization_servers: ['https://auth.example.com'] - }) - }); - } else if (urlString.includes('/.well-known/oauth-authorization-server')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - } - - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods - (providerWithCustomValidation.clientInformation as jest.Mock).mockResolvedValue({ - client_id: 'test-client', - client_secret: 'test-secret' - }); - (providerWithCustomValidation.tokens as jest.Mock).mockResolvedValue(undefined); - (providerWithCustomValidation.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); - (providerWithCustomValidation.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - - // Call auth - should succeed despite resource mismatch because custom validation overrides default - const result = await auth(providerWithCustomValidation, { - serverUrl: 'https://api.example.com/mcp-server' - }); - - expect(result).toBe('REDIRECT'); - - // Verify custom validation method was called - expect(mockValidateResourceURL).toHaveBeenCalledWith( - new URL('https://api.example.com/mcp-server'), - 'https://different-resource.example.com/mcp-server' - ); - }); - - it('uses prefix of server URL from PRM resource as resource parameter', async () => { - // Mock successful metadata discovery with resource URL that is a prefix of requested URL - mockFetch.mockImplementation(url => { - const urlString = url.toString(); - - if (urlString.includes('/.well-known/oauth-protected-resource')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - // Resource is a prefix of the requested server URL - resource: 'https://api.example.com/', - authorization_servers: ['https://auth.example.com'] - }) - }); - } else if (urlString.includes('/.well-known/oauth-authorization-server')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - } - - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: 'test-client', - client_secret: 'test-secret' - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); - (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); - (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - - // Call auth with a URL that has the resource as prefix - const result = await auth(mockProvider, { - serverUrl: 'https://api.example.com/mcp-server/endpoint' - }); - - expect(result).toBe('REDIRECT'); - - // Verify the authorization URL includes the resource parameter from PRM - expect(mockProvider.redirectToAuthorization).toHaveBeenCalledWith( - expect.objectContaining({ - searchParams: expect.any(URLSearchParams) - }) - ); - - const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; - const authUrl: URL = redirectCall[0]; - // Should use the PRM's resource value, not the full requested URL - expect(authUrl.searchParams.get('resource')).toBe('https://api.example.com/'); - }); - - it('excludes resource parameter when Protected Resource Metadata is not present', async () => { - // Mock metadata discovery where protected resource metadata is not available (404) - // but authorization server metadata is available - mockFetch.mockImplementation(url => { - const urlString = url.toString(); - - if (urlString.includes('/.well-known/oauth-protected-resource')) { - // Protected resource metadata not available - return Promise.resolve({ - ok: false, - status: 404 - }); - } else if (urlString.includes('/.well-known/oauth-authorization-server')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - } - - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: 'test-client', - client_secret: 'test-secret' - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); - (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); - (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - - // Call auth - should not include resource parameter - const result = await auth(mockProvider, { - serverUrl: 'https://api.example.com/mcp-server' - }); - - expect(result).toBe('REDIRECT'); - - // Verify the authorization URL does NOT include the resource parameter - expect(mockProvider.redirectToAuthorization).toHaveBeenCalledWith( - expect.objectContaining({ - searchParams: expect.any(URLSearchParams) - }) - ); - - const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; - const authUrl: URL = redirectCall[0]; - // Resource parameter should not be present when PRM is not available - expect(authUrl.searchParams.has('resource')).toBe(false); - }); - - it('excludes resource parameter in token exchange when Protected Resource Metadata is not present', async () => { - // Mock metadata discovery - no protected resource metadata, but auth server metadata available - mockFetch.mockImplementation(url => { - const urlString = url.toString(); - - if (urlString.includes('/.well-known/oauth-protected-resource')) { - return Promise.resolve({ - ok: false, - status: 404 - }); - } else if (urlString.includes('/.well-known/oauth-authorization-server')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - } else if (urlString.includes('/token')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - access_token: 'access123', - token_type: 'Bearer', - expires_in: 3600, - refresh_token: 'refresh123' - }) - }); - } - - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods for token exchange - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: 'test-client', - client_secret: 'test-secret' - }); - (mockProvider.codeVerifier as jest.Mock).mockResolvedValue('test-verifier'); - (mockProvider.saveTokens as jest.Mock).mockResolvedValue(undefined); - - // Call auth with authorization code - const result = await auth(mockProvider, { - serverUrl: 'https://api.example.com/mcp-server', - authorizationCode: 'auth-code-123' - }); - - expect(result).toBe('AUTHORIZED'); - - // Find the token exchange call - const tokenCall = mockFetch.mock.calls.find(call => call[0].toString().includes('/token')); - expect(tokenCall).toBeDefined(); - - const body = tokenCall![1].body as URLSearchParams; - // Resource parameter should not be present when PRM is not available - expect(body.has('resource')).toBe(false); - expect(body.get('code')).toBe('auth-code-123'); - }); - - it('excludes resource parameter in token refresh when Protected Resource Metadata is not present', async () => { - // Mock metadata discovery - no protected resource metadata, but auth server metadata available - mockFetch.mockImplementation(url => { - const urlString = url.toString(); - - if (urlString.includes('/.well-known/oauth-protected-resource')) { - return Promise.resolve({ - ok: false, - status: 404 - }); - } else if (urlString.includes('/.well-known/oauth-authorization-server')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - } else if (urlString.includes('/token')) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - access_token: 'new-access123', - token_type: 'Bearer', - expires_in: 3600 - }) - }); - } - - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods for token refresh - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: 'test-client', - client_secret: 'test-secret' - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue({ - access_token: 'old-access', - refresh_token: 'refresh123' - }); - (mockProvider.saveTokens as jest.Mock).mockResolvedValue(undefined); - - // Call auth with existing tokens (should trigger refresh) - const result = await auth(mockProvider, { - serverUrl: 'https://api.example.com/mcp-server' - }); - - expect(result).toBe('AUTHORIZED'); - - // Find the token refresh call - const tokenCall = mockFetch.mock.calls.find(call => call[0].toString().includes('/token')); - expect(tokenCall).toBeDefined(); - - const body = tokenCall![1].body as URLSearchParams; - // Resource parameter should not be present when PRM is not available - expect(body.has('resource')).toBe(false); - expect(body.get('grant_type')).toBe('refresh_token'); - expect(body.get('refresh_token')).toBe('refresh123'); - }); - - it('fetches AS metadata with path from serverUrl when PRM returns external AS', async () => { - // Mock PRM discovery that returns an external AS - mockFetch.mockImplementation(url => { - const urlString = url.toString(); - - if (urlString === 'https://my.resource.com/.well-known/oauth-protected-resource/path/name') { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - resource: 'https://my.resource.com/', - authorization_servers: ['https://auth.example.com/oauth'] - }) - }); - } else if (urlString === 'https://auth.example.com/.well-known/oauth-authorization-server/path/name') { - // Path-aware discovery on AS with path from serverUrl - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - } - - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: 'test-client', - client_secret: 'test-secret' - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); - (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); - (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - - // Call auth with serverUrl that has a path - const result = await auth(mockProvider, { - serverUrl: 'https://my.resource.com/path/name' - }); - - expect(result).toBe('REDIRECT'); - - // Verify the correct URLs were fetched - const calls = mockFetch.mock.calls; - - // First call should be to PRM - expect(calls[0][0].toString()).toBe('https://my.resource.com/.well-known/oauth-protected-resource/path/name'); - - // Second call should be to AS metadata with the path from authorization server - expect(calls[1][0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/oauth'); - }); - - it('supports overriding the fetch function used for requests', async () => { - const customFetch = jest.fn(); - - // Mock PRM discovery - customFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - resource: 'https://resource.example.com', - authorization_servers: ['https://auth.example.com'] - }) - }); - - // Mock AS metadata discovery - customFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - registration_endpoint: 'https://auth.example.com/register', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }); - - const mockProvider: OAuthClientProvider = { - get redirectUrl() { - return 'http://localhost:3000/callback'; - }, - get clientMetadata() { - return { - client_name: 'Test Client', - redirect_uris: ['http://localhost:3000/callback'] - }; - }, - clientInformation: jest.fn().mockResolvedValue({ - client_id: 'client123', - client_secret: 'secret123' - }), - tokens: jest.fn().mockResolvedValue(undefined), - saveTokens: jest.fn(), - redirectToAuthorization: jest.fn(), - saveCodeVerifier: jest.fn(), - codeVerifier: jest.fn().mockResolvedValue('verifier123') - }; - - const result = await auth(mockProvider, { - serverUrl: 'https://resource.example.com', - fetchFn: customFetch - }); - - expect(result).toBe('REDIRECT'); - expect(customFetch).toHaveBeenCalledTimes(2); - expect(mockFetch).not.toHaveBeenCalled(); - - // Verify custom fetch was called for PRM discovery - expect(customFetch.mock.calls[0][0].toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); - - // Verify custom fetch was called for AS metadata discovery - expect(customFetch.mock.calls[1][0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); - }); - }); - - describe('exchangeAuthorization with multiple client authentication methods', () => { - const validTokens = { - access_token: 'access123', - token_type: 'Bearer', - expires_in: 3600, - refresh_token: 'refresh123' - }; - - const validClientInfo = { - client_id: 'client123', - client_secret: 'secret123', - redirect_uris: ['http://localhost:3000/callback'], - client_name: 'Test Client' - }; - - const metadataWithBasicOnly = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/auth', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'], - token_endpoint_auth_methods_supported: ['client_secret_basic'] - }; - - const metadataWithPostOnly = { - ...metadataWithBasicOnly, - token_endpoint_auth_methods_supported: ['client_secret_post'] - }; - - const metadataWithNoneOnly = { - ...metadataWithBasicOnly, - token_endpoint_auth_methods_supported: ['none'] - }; - - const metadataWithAllBuiltinMethods = { - ...metadataWithBasicOnly, - token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post', 'none'] - }; - - it('uses HTTP Basic authentication when client_secret_basic is supported', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const tokens = await exchangeAuthorization('https://auth.example.com', { - metadata: metadataWithBasicOnly, - clientInformation: validClientInfo, - authorizationCode: 'code123', - redirectUri: 'http://localhost:3000/callback', - codeVerifier: 'verifier123' - }); - - expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0][1]; - - // Check Authorization header - const authHeader = request.headers.get('Authorization'); - const expected = 'Basic ' + btoa('client123:secret123'); - expect(authHeader).toBe(expected); - - const body = request.body as URLSearchParams; - expect(body.get('client_id')).toBeNull(); - expect(body.get('client_secret')).toBeNull(); - }); - - it('includes credentials in request body when client_secret_post is supported', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const tokens = await exchangeAuthorization('https://auth.example.com', { - metadata: metadataWithPostOnly, - clientInformation: validClientInfo, - authorizationCode: 'code123', - redirectUri: 'http://localhost:3000/callback', - codeVerifier: 'verifier123' - }); - - expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0][1]; - - // Check no Authorization header - expect(request.headers.get('Authorization')).toBeNull(); - - const body = request.body as URLSearchParams; - expect(body.get('client_id')).toBe('client123'); - expect(body.get('client_secret')).toBe('secret123'); - }); - - it('it picks client_secret_basic when all builtin methods are supported', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const tokens = await exchangeAuthorization('https://auth.example.com', { - metadata: metadataWithAllBuiltinMethods, - clientInformation: validClientInfo, - authorizationCode: 'code123', - redirectUri: 'http://localhost:3000/callback', - codeVerifier: 'verifier123' - }); - - expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0][1]; - - // Check Authorization header - should use Basic auth as it's the most secure - const authHeader = request.headers.get('Authorization'); - const expected = 'Basic ' + btoa('client123:secret123'); - expect(authHeader).toBe(expected); - - // Credentials should not be in body when using Basic auth - const body = request.body as URLSearchParams; - expect(body.get('client_id')).toBeNull(); - expect(body.get('client_secret')).toBeNull(); - }); - - it('uses public client authentication when none method is specified', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const clientInfoWithoutSecret = { - client_id: 'client123', - redirect_uris: ['http://localhost:3000/callback'], - client_name: 'Test Client' - }; - - const tokens = await exchangeAuthorization('https://auth.example.com', { - metadata: metadataWithNoneOnly, - clientInformation: clientInfoWithoutSecret, - authorizationCode: 'code123', - redirectUri: 'http://localhost:3000/callback', - codeVerifier: 'verifier123' - }); - - expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0][1]; - - // Check no Authorization header - expect(request.headers.get('Authorization')).toBeNull(); - - const body = request.body as URLSearchParams; - expect(body.get('client_id')).toBe('client123'); - expect(body.get('client_secret')).toBeNull(); - }); - - it('defaults to client_secret_post when no auth methods specified', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const tokens = await exchangeAuthorization('https://auth.example.com', { - clientInformation: validClientInfo, - authorizationCode: 'code123', - redirectUri: 'http://localhost:3000/callback', - codeVerifier: 'verifier123' - }); - - expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0][1]; - - // Check headers - expect(request.headers.get('Content-Type')).toBe('application/x-www-form-urlencoded'); - expect(request.headers.get('Authorization')).toBeNull(); - - const body = request.body as URLSearchParams; - expect(body.get('client_id')).toBe('client123'); - expect(body.get('client_secret')).toBe('secret123'); - }); - }); - - describe('refreshAuthorization with multiple client authentication methods', () => { - const validTokens = { - access_token: 'newaccess123', - token_type: 'Bearer', - expires_in: 3600, - refresh_token: 'newrefresh123' - }; - - const validClientInfo = { - client_id: 'client123', - client_secret: 'secret123', - redirect_uris: ['http://localhost:3000/callback'], - client_name: 'Test Client' - }; - - const metadataWithBasicOnly = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/auth', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - token_endpoint_auth_methods_supported: ['client_secret_basic'] - }; - - const metadataWithPostOnly = { - ...metadataWithBasicOnly, - token_endpoint_auth_methods_supported: ['client_secret_post'] - }; - - it('uses client_secret_basic for refresh token', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const tokens = await refreshAuthorization('https://auth.example.com', { - metadata: metadataWithBasicOnly, - clientInformation: validClientInfo, - refreshToken: 'refresh123' - }); - - expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0][1]; - - // Check Authorization header - const authHeader = request.headers.get('Authorization'); - const expected = 'Basic ' + btoa('client123:secret123'); - expect(authHeader).toBe(expected); - - const body = request.body as URLSearchParams; - expect(body.get('client_id')).toBeNull(); // should not be in body - expect(body.get('client_secret')).toBeNull(); // should not be in body - expect(body.get('refresh_token')).toBe('refresh123'); - }); - - it('uses client_secret_post for refresh token', async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens - }); - - const tokens = await refreshAuthorization('https://auth.example.com', { - metadata: metadataWithPostOnly, - clientInformation: validClientInfo, - refreshToken: 'refresh123' - }); - - expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0][1]; - - // Check no Authorization header - expect(request.headers.get('Authorization')).toBeNull(); - - const body = request.body as URLSearchParams; - expect(body.get('client_id')).toBe('client123'); - expect(body.get('client_secret')).toBe('secret123'); - expect(body.get('refresh_token')).toBe('refresh123'); - }); - }); -}); diff --git a/typescript-sdk/src/client/auth.ts b/typescript-sdk/src/client/auth.ts deleted file mode 100644 index 1e90f34..0000000 --- a/typescript-sdk/src/client/auth.ts +++ /dev/null @@ -1,1053 +0,0 @@ -import pkceChallenge from 'pkce-challenge'; -import { LATEST_PROTOCOL_VERSION } from '../types.js'; -import { - OAuthClientMetadata, - OAuthClientInformation, - OAuthTokens, - OAuthMetadata, - OAuthClientInformationFull, - OAuthProtectedResourceMetadata, - OAuthErrorResponseSchema, - AuthorizationServerMetadata, - OpenIdProviderDiscoveryMetadataSchema -} from '../shared/auth.js'; -import { - OAuthClientInformationFullSchema, - OAuthMetadataSchema, - OAuthProtectedResourceMetadataSchema, - OAuthTokensSchema -} from '../shared/auth.js'; -import { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js'; -import { - InvalidClientError, - InvalidGrantError, - OAUTH_ERRORS, - OAuthError, - ServerError, - UnauthorizedClientError -} from '../server/auth/errors.js'; -import { FetchLike } from '../shared/transport.js'; - -/** - * Implements an end-to-end OAuth client to be used with one MCP server. - * - * This client relies upon a concept of an authorized "session," the exact - * meaning of which is application-defined. Tokens, authorization codes, and - * code verifiers should not cross different sessions. - */ -export interface OAuthClientProvider { - /** - * The URL to redirect the user agent to after authorization. - */ - get redirectUrl(): string | URL; - - /** - * Metadata about this OAuth client. - */ - get clientMetadata(): OAuthClientMetadata; - - /** - * Returns a OAuth2 state parameter. - */ - state?(): string | Promise; - - /** - * Loads information about this OAuth client, as registered already with the - * server, or returns `undefined` if the client is not registered with the - * server. - */ - clientInformation(): OAuthClientInformation | undefined | Promise; - - /** - * If implemented, this permits the OAuth client to dynamically register with - * the server. Client information saved this way should later be read via - * `clientInformation()`. - * - * This method is not required to be implemented if client information is - * statically known (e.g., pre-registered). - */ - saveClientInformation?(clientInformation: OAuthClientInformationFull): void | Promise; - - /** - * Loads any existing OAuth tokens for the current session, or returns - * `undefined` if there are no saved tokens. - */ - tokens(): OAuthTokens | undefined | Promise; - - /** - * Stores new OAuth tokens for the current session, after a successful - * authorization. - */ - saveTokens(tokens: OAuthTokens): void | Promise; - - /** - * Invoked to redirect the user agent to the given URL to begin the authorization flow. - */ - redirectToAuthorization(authorizationUrl: URL): void | Promise; - - /** - * Saves a PKCE code verifier for the current session, before redirecting to - * the authorization flow. - */ - saveCodeVerifier(codeVerifier: string): void | Promise; - - /** - * Loads the PKCE code verifier for the current session, necessary to validate - * the authorization result. - */ - codeVerifier(): string | Promise; - - /** - * Adds custom client authentication to OAuth token requests. - * - * This optional method allows implementations to customize how client credentials - * are included in token exchange and refresh requests. When provided, this method - * is called instead of the default authentication logic, giving full control over - * the authentication mechanism. - * - * Common use cases include: - * - Supporting authentication methods beyond the standard OAuth 2.0 methods - * - Adding custom headers for proprietary authentication schemes - * - Implementing client assertion-based authentication (e.g., JWT bearer tokens) - * - * @param headers - The request headers (can be modified to add authentication) - * @param params - The request body parameters (can be modified to add credentials) - * @param url - The token endpoint URL being called - * @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods - */ - addClientAuthentication?( - headers: Headers, - params: URLSearchParams, - url: string | URL, - metadata?: AuthorizationServerMetadata - ): void | Promise; - - /** - * If defined, overrides the selection and validation of the - * RFC 8707 Resource Indicator. If left undefined, default - * validation behavior will be used. - * - * Implementations must verify the returned resource matches the MCP server. - */ - validateResourceURL?(serverUrl: string | URL, resource?: string): Promise; - - /** - * If implemented, provides a way for the client to invalidate (e.g. delete) the specified - * credentials, in the case where the server has indicated that they are no longer valid. - * This avoids requiring the user to intervene manually. - */ - invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier'): void | Promise; -} - -export type AuthResult = 'AUTHORIZED' | 'REDIRECT'; - -export class UnauthorizedError extends Error { - constructor(message?: string) { - super(message ?? 'Unauthorized'); - } -} - -type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none'; - -const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code'; -const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256'; - -/** - * Determines the best client authentication method to use based on server support and client configuration. - * - * Priority order (highest to lowest): - * 1. client_secret_basic (if client secret is available) - * 2. client_secret_post (if client secret is available) - * 3. none (for public clients) - * - * @param clientInformation - OAuth client information containing credentials - * @param supportedMethods - Authentication methods supported by the authorization server - * @returns The selected authentication method - */ -function selectClientAuthMethod(clientInformation: OAuthClientInformation, supportedMethods: string[]): ClientAuthMethod { - const hasClientSecret = clientInformation.client_secret !== undefined; - - // If server doesn't specify supported methods, use RFC 6749 defaults - if (supportedMethods.length === 0) { - return hasClientSecret ? 'client_secret_post' : 'none'; - } - - // Try methods in priority order (most secure first) - if (hasClientSecret && supportedMethods.includes('client_secret_basic')) { - return 'client_secret_basic'; - } - - if (hasClientSecret && supportedMethods.includes('client_secret_post')) { - return 'client_secret_post'; - } - - if (supportedMethods.includes('none')) { - return 'none'; - } - - // Fallback: use what we have - return hasClientSecret ? 'client_secret_post' : 'none'; -} - -/** - * Applies client authentication to the request based on the specified method. - * - * Implements OAuth 2.1 client authentication methods: - * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1) - * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1) - * - none: Public client authentication (RFC 6749 Section 2.1) - * - * @param method - The authentication method to use - * @param clientInformation - OAuth client information containing credentials - * @param headers - HTTP headers object to modify - * @param params - URL search parameters to modify - * @throws {Error} When required credentials are missing - */ -function applyClientAuthentication( - method: ClientAuthMethod, - clientInformation: OAuthClientInformation, - headers: Headers, - params: URLSearchParams -): void { - const { client_id, client_secret } = clientInformation; - - switch (method) { - case 'client_secret_basic': - applyBasicAuth(client_id, client_secret, headers); - return; - case 'client_secret_post': - applyPostAuth(client_id, client_secret, params); - return; - case 'none': - applyPublicAuth(client_id, params); - return; - default: - throw new Error(`Unsupported client authentication method: ${method}`); - } -} - -/** - * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1) - */ -function applyBasicAuth(clientId: string, clientSecret: string | undefined, headers: Headers): void { - if (!clientSecret) { - throw new Error('client_secret_basic authentication requires a client_secret'); - } - - const credentials = btoa(`${clientId}:${clientSecret}`); - headers.set('Authorization', `Basic ${credentials}`); -} - -/** - * Applies POST body authentication (RFC 6749 Section 2.3.1) - */ -function applyPostAuth(clientId: string, clientSecret: string | undefined, params: URLSearchParams): void { - params.set('client_id', clientId); - if (clientSecret) { - params.set('client_secret', clientSecret); - } -} - -/** - * Applies public client authentication (RFC 6749 Section 2.1) - */ -function applyPublicAuth(clientId: string, params: URLSearchParams): void { - params.set('client_id', clientId); -} - -/** - * Parses an OAuth error response from a string or Response object. - * - * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec - * and an instance of the appropriate OAuthError subclass will be returned. - * If parsing fails, it falls back to a generic ServerError that includes - * the response status (if available) and original content. - * - * @param input - A Response object or string containing the error response - * @returns A Promise that resolves to an OAuthError instance - */ -export async function parseErrorResponse(input: Response | string): Promise { - const statusCode = input instanceof Response ? input.status : undefined; - const body = input instanceof Response ? await input.text() : input; - - try { - const result = OAuthErrorResponseSchema.parse(JSON.parse(body)); - const { error, error_description, error_uri } = result; - const errorClass = OAUTH_ERRORS[error] || ServerError; - return new errorClass(error_description || '', error_uri); - } catch (error) { - // Not a valid OAuth error response, but try to inform the user of the raw data anyway - const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`; - return new ServerError(errorMessage); - } -} - -/** - * Orchestrates the full auth flow with a server. - * - * This can be used as a single entry point for all authorization functionality, - * instead of linking together the other lower-level functions in this module. - */ -export async function auth( - provider: OAuthClientProvider, - options: { - serverUrl: string | URL; - authorizationCode?: string; - scope?: string; - resourceMetadataUrl?: URL; - fetchFn?: FetchLike; - } -): Promise { - try { - return await authInternal(provider, options); - } catch (error) { - // Handle recoverable error types by invalidating credentials and retrying - if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) { - await provider.invalidateCredentials?.('all'); - return await authInternal(provider, options); - } else if (error instanceof InvalidGrantError) { - await provider.invalidateCredentials?.('tokens'); - return await authInternal(provider, options); - } - - // Throw otherwise - throw error; - } -} - -async function authInternal( - provider: OAuthClientProvider, - { - serverUrl, - authorizationCode, - scope, - resourceMetadataUrl, - fetchFn - }: { - serverUrl: string | URL; - authorizationCode?: string; - scope?: string; - resourceMetadataUrl?: URL; - fetchFn?: FetchLike; - } -): Promise { - let resourceMetadata: OAuthProtectedResourceMetadata | undefined; - let authorizationServerUrl: string | URL | undefined; - try { - resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn); - if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { - authorizationServerUrl = resourceMetadata.authorization_servers[0]; - } - } catch { - // Ignore errors and fall back to /.well-known/oauth-authorization-server - } - - /** - * If we don't get a valid authorization server metadata from protected resource metadata, - * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server acts as the Authorization server. - */ - if (!authorizationServerUrl) { - authorizationServerUrl = serverUrl; - } - - const resource: URL | undefined = await selectResourceURL(serverUrl, provider, resourceMetadata); - - const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { - fetchFn - }); - - // Handle client registration if needed - let clientInformation = await Promise.resolve(provider.clientInformation()); - if (!clientInformation) { - if (authorizationCode !== undefined) { - throw new Error('Existing OAuth client information is required when exchanging an authorization code'); - } - - if (!provider.saveClientInformation) { - throw new Error('OAuth client information must be saveable for dynamic registration'); - } - - const fullInformation = await registerClient(authorizationServerUrl, { - metadata, - clientMetadata: provider.clientMetadata, - fetchFn - }); - - await provider.saveClientInformation(fullInformation); - clientInformation = fullInformation; - } - - // Exchange authorization code for tokens - if (authorizationCode !== undefined) { - const codeVerifier = await provider.codeVerifier(); - const tokens = await exchangeAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - authorizationCode, - codeVerifier, - redirectUri: provider.redirectUrl, - resource, - addClientAuthentication: provider.addClientAuthentication, - fetchFn: fetchFn - }); - - await provider.saveTokens(tokens); - return 'AUTHORIZED'; - } - - const tokens = await provider.tokens(); - - // Handle token refresh or new authorization - if (tokens?.refresh_token) { - try { - // Attempt to refresh the token - const newTokens = await refreshAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - refreshToken: tokens.refresh_token, - resource, - addClientAuthentication: provider.addClientAuthentication, - fetchFn - }); - - await provider.saveTokens(newTokens); - return 'AUTHORIZED'; - } catch (error) { - // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry. - if (!(error instanceof OAuthError) || error instanceof ServerError) { - // Could not refresh OAuth tokens - } else { - // Refresh failed for another reason, re-throw - throw error; - } - } - } - - const state = provider.state ? await provider.state() : undefined; - - // Start new authorization flow - const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - state, - redirectUrl: provider.redirectUrl, - scope: scope || provider.clientMetadata.scope, - resource - }); - - await provider.saveCodeVerifier(codeVerifier); - await provider.redirectToAuthorization(authorizationUrl); - return 'REDIRECT'; -} - -export async function selectResourceURL( - serverUrl: string | URL, - provider: OAuthClientProvider, - resourceMetadata?: OAuthProtectedResourceMetadata -): Promise { - const defaultResource = resourceUrlFromServerUrl(serverUrl); - - // If provider has custom validation, delegate to it - if (provider.validateResourceURL) { - return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource); - } - - // Only include resource parameter when Protected Resource Metadata is present - if (!resourceMetadata) { - return undefined; - } - - // Validate that the metadata's resource is compatible with our request - if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { - throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); - } - // Prefer the resource from metadata since it's what the server is telling us to request - return new URL(resourceMetadata.resource); -} - -/** - * Extract resource_metadata from response header. - */ -export function extractResourceMetadataUrl(res: Response): URL | undefined { - const authenticateHeader = res.headers.get('WWW-Authenticate'); - if (!authenticateHeader) { - return undefined; - } - - const [type, scheme] = authenticateHeader.split(' '); - if (type.toLowerCase() !== 'bearer' || !scheme) { - return undefined; - } - const regex = /resource_metadata="([^"]*)"/; - const match = regex.exec(authenticateHeader); - - if (!match) { - return undefined; - } - - try { - return new URL(match[1]); - } catch { - return undefined; - } -} - -/** - * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. - * - * If the server returns a 404 for the well-known endpoint, this function will - * return `undefined`. Any other errors will be thrown as exceptions. - */ -export async function discoverOAuthProtectedResourceMetadata( - serverUrl: string | URL, - opts?: { protocolVersion?: string; resourceMetadataUrl?: string | URL }, - fetchFn: FetchLike = fetch -): Promise { - const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, { - protocolVersion: opts?.protocolVersion, - metadataUrl: opts?.resourceMetadataUrl - }); - - if (!response || response.status === 404) { - throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); - } - - if (!response.ok) { - throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); - } - return OAuthProtectedResourceMetadataSchema.parse(await response.json()); -} - -/** - * Helper function to handle fetch with CORS retry logic - */ -async function fetchWithCorsRetry(url: URL, headers?: Record, fetchFn: FetchLike = fetch): Promise { - try { - return await fetchFn(url, { headers }); - } catch (error) { - if (error instanceof TypeError) { - if (headers) { - // CORS errors come back as TypeError, retry without headers - return fetchWithCorsRetry(url, undefined, fetchFn); - } else { - // We're getting CORS errors on retry too, return undefined - return undefined; - } - } - throw error; - } -} - -/** - * Constructs the well-known path for auth-related metadata discovery - */ -function buildWellKnownPath( - wellKnownPrefix: 'oauth-authorization-server' | 'oauth-protected-resource' | 'openid-configuration', - pathname: string = '', - options: { prependPathname?: boolean } = {} -): string { - // Strip trailing slash from pathname to avoid double slashes - if (pathname.endsWith('/')) { - pathname = pathname.slice(0, -1); - } - - return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; -} - -/** - * Tries to discover OAuth metadata at a specific URL - */ -async function tryMetadataDiscovery(url: URL, protocolVersion: string, fetchFn: FetchLike = fetch): Promise { - const headers = { - 'MCP-Protocol-Version': protocolVersion - }; - return await fetchWithCorsRetry(url, headers, fetchFn); -} - -/** - * Determines if fallback to root discovery should be attempted - */ -function shouldAttemptFallback(response: Response | undefined, pathname: string): boolean { - return !response || (response.status >= 400 && response.status < 500 && pathname !== '/'); -} - -/** - * Generic function for discovering OAuth metadata with fallback support - */ -async function discoverMetadataWithFallback( - serverUrl: string | URL, - wellKnownType: 'oauth-authorization-server' | 'oauth-protected-resource', - fetchFn: FetchLike, - opts?: { protocolVersion?: string; metadataUrl?: string | URL; metadataServerUrl?: string | URL } -): Promise { - const issuer = new URL(serverUrl); - const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION; - - let url: URL; - if (opts?.metadataUrl) { - url = new URL(opts.metadataUrl); - } else { - // Try path-aware discovery first - const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); - url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer); - url.search = issuer.search; - } - - let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn); - - // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery - if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) { - const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer); - response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn); - } - - return response; -} - -/** - * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. - * - * If the server returns a 404 for the well-known endpoint, this function will - * return `undefined`. Any other errors will be thrown as exceptions. - * - * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. - */ -export async function discoverOAuthMetadata( - issuer: string | URL, - { - authorizationServerUrl, - protocolVersion - }: { - authorizationServerUrl?: string | URL; - protocolVersion?: string; - } = {}, - fetchFn: FetchLike = fetch -): Promise { - if (typeof issuer === 'string') { - issuer = new URL(issuer); - } - if (!authorizationServerUrl) { - authorizationServerUrl = issuer; - } - if (typeof authorizationServerUrl === 'string') { - authorizationServerUrl = new URL(authorizationServerUrl); - } - protocolVersion ??= LATEST_PROTOCOL_VERSION; - - const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, { - protocolVersion, - metadataServerUrl: authorizationServerUrl - }); - - if (!response || response.status === 404) { - return undefined; - } - - if (!response.ok) { - throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`); - } - - return OAuthMetadataSchema.parse(await response.json()); -} - -/** - * Builds a list of discovery URLs to try for authorization server metadata. - * URLs are returned in priority order: - * 1. OAuth metadata at the given URL - * 2. OAuth metadata at root (if URL has path) - * 3. OIDC metadata endpoints - */ -export function buildDiscoveryUrls(authorizationServerUrl: string | URL): { url: URL; type: 'oauth' | 'oidc' }[] { - const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl; - const hasPath = url.pathname !== '/'; - const urlsToTry: { url: URL; type: 'oauth' | 'oidc' }[] = []; - - if (!hasPath) { - // Root path: https://example.com/.well-known/oauth-authorization-server - urlsToTry.push({ - url: new URL('/.well-known/oauth-authorization-server', url.origin), - type: 'oauth' - }); - - // OIDC: https://example.com/.well-known/openid-configuration - urlsToTry.push({ - url: new URL(`/.well-known/openid-configuration`, url.origin), - type: 'oidc' - }); - - return urlsToTry; - } - - // Strip trailing slash from pathname to avoid double slashes - let pathname = url.pathname; - if (pathname.endsWith('/')) { - pathname = pathname.slice(0, -1); - } - - // 1. OAuth metadata at the given URL - // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1 - urlsToTry.push({ - url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin), - type: 'oauth' - }); - - // Root path: https://example.com/.well-known/oauth-authorization-server - urlsToTry.push({ - url: new URL('/.well-known/oauth-authorization-server', url.origin), - type: 'oauth' - }); - - // 3. OIDC metadata endpoints - // RFC 8414 style: Insert /.well-known/openid-configuration before the path - urlsToTry.push({ - url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin), - type: 'oidc' - }); - // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path - urlsToTry.push({ - url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin), - type: 'oidc' - }); - - return urlsToTry; -} - -/** - * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata - * and OpenID Connect Discovery 1.0 specifications. - * - * This function implements a fallback strategy for authorization server discovery: - * 1. Attempts RFC 8414 OAuth metadata discovery first - * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery - * - * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's - * protected resource metadata, or the MCP server's URL if the - * metadata was not found. - * @param options - Configuration options - * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch - * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION - * @returns Promise resolving to authorization server metadata, or undefined if discovery fails - */ -export async function discoverAuthorizationServerMetadata( - authorizationServerUrl: string | URL, - { - fetchFn = fetch, - protocolVersion = LATEST_PROTOCOL_VERSION - }: { - fetchFn?: FetchLike; - protocolVersion?: string; - } = {} -): Promise { - const headers = { - 'MCP-Protocol-Version': protocolVersion, - Accept: 'application/json' - }; - - // Get the list of URLs to try - const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); - - // Try each URL in order - for (const { url: endpointUrl, type } of urlsToTry) { - const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); - - if (!response) { - /** - * CORS error occurred - don't throw as the endpoint may not allow CORS, - * continue trying other possible endpoints - */ - continue; - } - - if (!response.ok) { - // Continue looking for any 4xx response code. - if (response.status >= 400 && response.status < 500) { - continue; // Try next URL - } - throw new Error( - `HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}` - ); - } - - // Parse and validate based on type - if (type === 'oauth') { - return OAuthMetadataSchema.parse(await response.json()); - } else { - return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); - } - } - - return undefined; -} - -/** - * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. - */ -export async function startAuthorization( - authorizationServerUrl: string | URL, - { - metadata, - clientInformation, - redirectUrl, - scope, - state, - resource - }: { - metadata?: AuthorizationServerMetadata; - clientInformation: OAuthClientInformation; - redirectUrl: string | URL; - scope?: string; - state?: string; - resource?: URL; - } -): Promise<{ authorizationUrl: URL; codeVerifier: string }> { - let authorizationUrl: URL; - if (metadata) { - authorizationUrl = new URL(metadata.authorization_endpoint); - - if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) { - throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); - } - - if ( - metadata.code_challenge_methods_supported && - !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD) - ) { - throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); - } - } else { - authorizationUrl = new URL('/authorize', authorizationServerUrl); - } - - // Generate PKCE challenge - const challenge = await pkceChallenge(); - const codeVerifier = challenge.code_verifier; - const codeChallenge = challenge.code_challenge; - - authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE); - authorizationUrl.searchParams.set('client_id', clientInformation.client_id); - authorizationUrl.searchParams.set('code_challenge', codeChallenge); - authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD); - authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl)); - - if (state) { - authorizationUrl.searchParams.set('state', state); - } - - if (scope) { - authorizationUrl.searchParams.set('scope', scope); - } - - if (scope?.includes('offline_access')) { - // if the request includes the OIDC-only "offline_access" scope, - // we need to set the prompt to "consent" to ensure the user is prompted to grant offline access - // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess - authorizationUrl.searchParams.append('prompt', 'consent'); - } - - if (resource) { - authorizationUrl.searchParams.set('resource', resource.href); - } - - return { authorizationUrl, codeVerifier }; -} - -/** - * Exchanges an authorization code for an access token with the given server. - * - * Supports multiple client authentication methods as specified in OAuth 2.1: - * - Automatically selects the best authentication method based on server support - * - Falls back to appropriate defaults when server metadata is unavailable - * - * @param authorizationServerUrl - The authorization server's base URL - * @param options - Configuration object containing client info, auth code, etc. - * @returns Promise resolving to OAuth tokens - * @throws {Error} When token exchange fails or authentication is invalid - */ -export async function exchangeAuthorization( - authorizationServerUrl: string | URL, - { - metadata, - clientInformation, - authorizationCode, - codeVerifier, - redirectUri, - resource, - addClientAuthentication, - fetchFn - }: { - metadata?: AuthorizationServerMetadata; - clientInformation: OAuthClientInformation; - authorizationCode: string; - codeVerifier: string; - redirectUri: string | URL; - resource?: URL; - addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; - fetchFn?: FetchLike; - } -): Promise { - const grantType = 'authorization_code'; - - const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl); - - if (metadata?.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) { - throw new Error(`Incompatible auth server: does not support grant type ${grantType}`); - } - - // Exchange code for tokens - const headers = new Headers({ - 'Content-Type': 'application/x-www-form-urlencoded', - Accept: 'application/json' - }); - const params = new URLSearchParams({ - grant_type: grantType, - code: authorizationCode, - code_verifier: codeVerifier, - redirect_uri: String(redirectUri) - }); - - if (addClientAuthentication) { - addClientAuthentication(headers, params, authorizationServerUrl, metadata); - } else { - // Determine and apply client authentication method - const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? []; - const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); - - applyClientAuthentication(authMethod, clientInformation, headers, params); - } - - if (resource) { - params.set('resource', resource.href); - } - - const response = await (fetchFn ?? fetch)(tokenUrl, { - method: 'POST', - headers, - body: params - }); - - if (!response.ok) { - throw await parseErrorResponse(response); - } - - return OAuthTokensSchema.parse(await response.json()); -} - -/** - * Exchange a refresh token for an updated access token. - * - * Supports multiple client authentication methods as specified in OAuth 2.1: - * - Automatically selects the best authentication method based on server support - * - Preserves the original refresh token if a new one is not returned - * - * @param authorizationServerUrl - The authorization server's base URL - * @param options - Configuration object containing client info, refresh token, etc. - * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) - * @throws {Error} When token refresh fails or authentication is invalid - */ -export async function refreshAuthorization( - authorizationServerUrl: string | URL, - { - metadata, - clientInformation, - refreshToken, - resource, - addClientAuthentication, - fetchFn - }: { - metadata?: AuthorizationServerMetadata; - clientInformation: OAuthClientInformation; - refreshToken: string; - resource?: URL; - addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; - fetchFn?: FetchLike; - } -): Promise { - const grantType = 'refresh_token'; - - let tokenUrl: URL; - if (metadata) { - tokenUrl = new URL(metadata.token_endpoint); - - if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) { - throw new Error(`Incompatible auth server: does not support grant type ${grantType}`); - } - } else { - tokenUrl = new URL('/token', authorizationServerUrl); - } - - // Exchange refresh token - const headers = new Headers({ - 'Content-Type': 'application/x-www-form-urlencoded' - }); - const params = new URLSearchParams({ - grant_type: grantType, - refresh_token: refreshToken - }); - - if (addClientAuthentication) { - addClientAuthentication(headers, params, authorizationServerUrl, metadata); - } else { - // Determine and apply client authentication method - const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? []; - const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); - - applyClientAuthentication(authMethod, clientInformation, headers, params); - } - - if (resource) { - params.set('resource', resource.href); - } - - const response = await (fetchFn ?? fetch)(tokenUrl, { - method: 'POST', - headers, - body: params - }); - if (!response.ok) { - throw await parseErrorResponse(response); - } - - return OAuthTokensSchema.parse({ refresh_token: refreshToken, ...(await response.json()) }); -} - -/** - * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. - */ -export async function registerClient( - authorizationServerUrl: string | URL, - { - metadata, - clientMetadata, - fetchFn - }: { - metadata?: AuthorizationServerMetadata; - clientMetadata: OAuthClientMetadata; - fetchFn?: FetchLike; - } -): Promise { - let registrationUrl: URL; - - if (metadata) { - if (!metadata.registration_endpoint) { - throw new Error('Incompatible auth server: does not support dynamic client registration'); - } - - registrationUrl = new URL(metadata.registration_endpoint); - } else { - registrationUrl = new URL('/register', authorizationServerUrl); - } - - const response = await (fetchFn ?? fetch)(registrationUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(clientMetadata) - }); - - if (!response.ok) { - throw await parseErrorResponse(response); - } - - return OAuthClientInformationFullSchema.parse(await response.json()); -} diff --git a/typescript-sdk/src/client/cross-spawn.test.ts b/typescript-sdk/src/client/cross-spawn.test.ts deleted file mode 100644 index ca2a500..0000000 --- a/typescript-sdk/src/client/cross-spawn.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { StdioClientTransport, getDefaultEnvironment } from './stdio.js'; -import spawn from 'cross-spawn'; -import { JSONRPCMessage } from '../types.js'; -import { ChildProcess } from 'node:child_process'; - -// mock cross-spawn -jest.mock('cross-spawn'); -const mockSpawn = spawn as jest.MockedFunction; - -describe('StdioClientTransport using cross-spawn', () => { - beforeEach(() => { - // mock cross-spawn's return value - mockSpawn.mockImplementation(() => { - const mockProcess: { - on: jest.Mock; - stdin?: { on: jest.Mock; write: jest.Mock }; - stdout?: { on: jest.Mock }; - stderr?: null; - } = { - on: jest.fn((event: string, callback: () => void) => { - if (event === 'spawn') { - callback(); - } - return mockProcess; - }), - stdin: { - on: jest.fn(), - write: jest.fn().mockReturnValue(true) - }, - stdout: { - on: jest.fn() - }, - stderr: null - }; - return mockProcess as unknown as ChildProcess; - }); - }); - - afterEach(() => { - jest.clearAllMocks(); - }); - - test('should call cross-spawn correctly', async () => { - const transport = new StdioClientTransport({ - command: 'test-command', - args: ['arg1', 'arg2'] - }); - - await transport.start(); - - // verify spawn is called correctly - expect(mockSpawn).toHaveBeenCalledWith( - 'test-command', - ['arg1', 'arg2'], - expect.objectContaining({ - shell: false - }) - ); - }); - - test('should pass environment variables correctly', async () => { - const customEnv = { TEST_VAR: 'test-value' }; - const transport = new StdioClientTransport({ - command: 'test-command', - env: customEnv - }); - - await transport.start(); - - // verify environment variables are merged correctly - expect(mockSpawn).toHaveBeenCalledWith( - 'test-command', - [], - expect.objectContaining({ - env: { - ...getDefaultEnvironment(), - ...customEnv - } - }) - ); - }); - - test('should use default environment when env is undefined', async () => { - const transport = new StdioClientTransport({ - command: 'test-command', - env: undefined - }); - - await transport.start(); - - // verify default environment is used - expect(mockSpawn).toHaveBeenCalledWith( - 'test-command', - [], - expect.objectContaining({ - env: getDefaultEnvironment() - }) - ); - }); - - test('should send messages correctly', async () => { - const transport = new StdioClientTransport({ - command: 'test-command' - }); - - // get the mock process object - const mockProcess: { - on: jest.Mock; - stdin: { - on: jest.Mock; - write: jest.Mock; - once: jest.Mock; - }; - stdout: { - on: jest.Mock; - }; - stderr: null; - } = { - on: jest.fn((event: string, callback: () => void) => { - if (event === 'spawn') { - callback(); - } - return mockProcess; - }), - stdin: { - on: jest.fn(), - write: jest.fn().mockReturnValue(true), - once: jest.fn() - }, - stdout: { - on: jest.fn() - }, - stderr: null - }; - - mockSpawn.mockReturnValue(mockProcess as unknown as ChildProcess); - - await transport.start(); - - // 关键修复:确保 jsonrpc 是字面量 "2.0" - const message: JSONRPCMessage = { - jsonrpc: '2.0', - id: 'test-id', - method: 'test-method' - }; - - await transport.send(message); - - // verify message is sent correctly - expect(mockProcess.stdin.write).toHaveBeenCalled(); - }); -}); diff --git a/typescript-sdk/src/client/index.test.ts b/typescript-sdk/src/client/index.test.ts deleted file mode 100644 index de37b2d..0000000 --- a/typescript-sdk/src/client/index.test.ts +++ /dev/null @@ -1,1241 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ -/* eslint-disable no-constant-binary-expression */ -/* eslint-disable @typescript-eslint/no-unused-expressions */ -import { Client } from './index.js'; -import { z } from 'zod'; -import { - RequestSchema, - NotificationSchema, - ResultSchema, - LATEST_PROTOCOL_VERSION, - SUPPORTED_PROTOCOL_VERSIONS, - InitializeRequestSchema, - ListResourcesRequestSchema, - ListToolsRequestSchema, - CallToolRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema, - ErrorCode -} from '../types.js'; -import { Transport } from '../shared/transport.js'; -import { Server } from '../server/index.js'; -import { InMemoryTransport } from '../inMemory.js'; - -/*** - * Test: Initialize with Matching Protocol Version - */ -test('should initialize with matching protocol version', async () => { - const clientTransport: Transport = { - start: jest.fn().mockResolvedValue(undefined), - close: jest.fn().mockResolvedValue(undefined), - send: jest.fn().mockImplementation(message => { - if (message.method === 'initialize') { - clientTransport.onmessage?.({ - jsonrpc: '2.0', - id: message.id, - result: { - protocolVersion: LATEST_PROTOCOL_VERSION, - capabilities: {}, - serverInfo: { - name: 'test', - version: '1.0' - }, - instructions: 'test instructions' - } - }); - } - return Promise.resolve(); - }) - }; - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - await client.connect(clientTransport); - - // Should have sent initialize with latest version - expect(clientTransport.send).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'initialize', - params: expect.objectContaining({ - protocolVersion: LATEST_PROTOCOL_VERSION - }) - }), - expect.objectContaining({ - relatedRequestId: undefined - }) - ); - - // Should have the instructions returned - expect(client.getInstructions()).toEqual('test instructions'); -}); - -/*** - * Test: Initialize with Supported Older Protocol Version - */ -test('should initialize with supported older protocol version', async () => { - const OLD_VERSION = SUPPORTED_PROTOCOL_VERSIONS[1]; - const clientTransport: Transport = { - start: jest.fn().mockResolvedValue(undefined), - close: jest.fn().mockResolvedValue(undefined), - send: jest.fn().mockImplementation(message => { - if (message.method === 'initialize') { - clientTransport.onmessage?.({ - jsonrpc: '2.0', - id: message.id, - result: { - protocolVersion: OLD_VERSION, - capabilities: {}, - serverInfo: { - name: 'test', - version: '1.0' - } - } - }); - } - return Promise.resolve(); - }) - }; - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - await client.connect(clientTransport); - - // Connection should succeed with the older version - expect(client.getServerVersion()).toEqual({ - name: 'test', - version: '1.0' - }); - - // Expect no instructions - expect(client.getInstructions()).toBeUndefined(); -}); - -/*** - * Test: Reject Unsupported Protocol Version - */ -test('should reject unsupported protocol version', async () => { - const clientTransport: Transport = { - start: jest.fn().mockResolvedValue(undefined), - close: jest.fn().mockResolvedValue(undefined), - send: jest.fn().mockImplementation(message => { - if (message.method === 'initialize') { - clientTransport.onmessage?.({ - jsonrpc: '2.0', - id: message.id, - result: { - protocolVersion: 'invalid-version', - capabilities: {}, - serverInfo: { - name: 'test', - version: '1.0' - } - } - }); - } - return Promise.resolve(); - }) - }; - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - await expect(client.connect(clientTransport)).rejects.toThrow("Server's protocol version is not supported: invalid-version"); - - expect(clientTransport.close).toHaveBeenCalled(); -}); - -/*** - * Test: Connect New Client to Old Supported Server Version - */ -test('should connect new client to old, supported server version', async () => { - const OLD_VERSION = SUPPORTED_PROTOCOL_VERSIONS[1]; - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - resources: {}, - tools: {} - } - } - ); - - server.setRequestHandler(InitializeRequestSchema, _request => ({ - protocolVersion: OLD_VERSION, - capabilities: { - resources: {}, - tools: {} - }, - serverInfo: { - name: 'old server', - version: '1.0' - } - })); - - server.setRequestHandler(ListResourcesRequestSchema, () => ({ - resources: [] - })); - - server.setRequestHandler(ListToolsRequestSchema, () => ({ - tools: [] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const client = new Client( - { - name: 'new client', - version: '1.0', - protocolVersion: LATEST_PROTOCOL_VERSION - }, - { - capabilities: { - sampling: {} - }, - enforceStrictCapabilities: true - } - ); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - expect(client.getServerVersion()).toEqual({ - name: 'old server', - version: '1.0' - }); -}); - -/*** - * Test: Version Negotiation with Old Client and Newer Server - */ -test('should negotiate version when client is old, and newer server supports its version', async () => { - const OLD_VERSION = SUPPORTED_PROTOCOL_VERSIONS[1]; - const server = new Server( - { - name: 'new server', - version: '1.0' - }, - { - capabilities: { - resources: {}, - tools: {} - } - } - ); - - server.setRequestHandler(InitializeRequestSchema, _request => ({ - protocolVersion: LATEST_PROTOCOL_VERSION, - capabilities: { - resources: {}, - tools: {} - }, - serverInfo: { - name: 'new server', - version: '1.0' - } - })); - - server.setRequestHandler(ListResourcesRequestSchema, () => ({ - resources: [] - })); - - server.setRequestHandler(ListToolsRequestSchema, () => ({ - tools: [] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const client = new Client( - { - name: 'old client', - version: '1.0', - protocolVersion: OLD_VERSION - }, - { - capabilities: { - sampling: {} - }, - enforceStrictCapabilities: true - } - ); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - expect(client.getServerVersion()).toEqual({ - name: 'new server', - version: '1.0' - }); -}); - -/*** - * Test: Throw when Old Client and Server Version Mismatch - */ -test("should throw when client is old, and server doesn't support its version", async () => { - const OLD_VERSION = SUPPORTED_PROTOCOL_VERSIONS[1]; - const FUTURE_VERSION = 'FUTURE_VERSION'; - const server = new Server( - { - name: 'new server', - version: '1.0' - }, - { - capabilities: { - resources: {}, - tools: {} - } - } - ); - - server.setRequestHandler(InitializeRequestSchema, _request => ({ - protocolVersion: FUTURE_VERSION, - capabilities: { - resources: {}, - tools: {} - }, - serverInfo: { - name: 'new server', - version: '1.0' - } - })); - - server.setRequestHandler(ListResourcesRequestSchema, () => ({ - resources: [] - })); - - server.setRequestHandler(ListToolsRequestSchema, () => ({ - tools: [] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const client = new Client( - { - name: 'old client', - version: '1.0', - protocolVersion: OLD_VERSION - }, - { - capabilities: { - sampling: {} - }, - enforceStrictCapabilities: true - } - ); - - await Promise.all([ - expect(client.connect(clientTransport)).rejects.toThrow("Server's protocol version is not supported: FUTURE_VERSION"), - server.connect(serverTransport) - ]); -}); - -/*** - * Test: Respect Server Capabilities - */ -test('should respect server capabilities', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - resources: {}, - tools: {} - } - } - ); - - server.setRequestHandler(InitializeRequestSchema, _request => ({ - protocolVersion: LATEST_PROTOCOL_VERSION, - capabilities: { - resources: {}, - tools: {} - }, - serverInfo: { - name: 'test', - version: '1.0' - } - })); - - server.setRequestHandler(ListResourcesRequestSchema, () => ({ - resources: [] - })); - - server.setRequestHandler(ListToolsRequestSchema, () => ({ - tools: [] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - sampling: {} - }, - enforceStrictCapabilities: true - } - ); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // Server supports resources and tools, but not prompts - expect(client.getServerCapabilities()).toEqual({ - resources: {}, - tools: {} - }); - - // These should work - await expect(client.listResources()).resolves.not.toThrow(); - await expect(client.listTools()).resolves.not.toThrow(); - - // These should throw because prompts, logging, and completions are not supported - await expect(client.listPrompts()).rejects.toThrow('Server does not support prompts'); - await expect(client.setLoggingLevel('error')).rejects.toThrow('Server does not support logging'); - await expect( - client.complete({ - ref: { type: 'ref/prompt', name: 'test' }, - argument: { name: 'test', value: 'test' } - }) - ).rejects.toThrow('Server does not support completions'); -}); - -/*** - * Test: Respect Client Notification Capabilities - */ -test('should respect client notification capabilities', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: {} - } - ); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - roots: { - listChanged: true - } - } - } - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // This should work because the client has the roots.listChanged capability - await expect(client.sendRootsListChanged()).resolves.not.toThrow(); - - // Create a new client without the roots.listChanged capability - const clientWithoutCapability = new Client( - { - name: 'test client without capability', - version: '1.0' - }, - { - capabilities: {}, - enforceStrictCapabilities: true - } - ); - - await clientWithoutCapability.connect(clientTransport); - - // This should throw because the client doesn't have the roots.listChanged capability - await expect(clientWithoutCapability.sendRootsListChanged()).rejects.toThrow(/^Client does not support/); -}); - -/*** - * Test: Respect Server Notification Capabilities - */ -test('should respect server notification capabilities', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - logging: {}, - resources: { - listChanged: true - } - } - } - ); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: {} - } - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // These should work because the server has the corresponding capabilities - await expect(server.sendLoggingMessage({ level: 'info', data: 'Test' })).resolves.not.toThrow(); - await expect(server.sendResourceListChanged()).resolves.not.toThrow(); - - // This should throw because the server doesn't have the tools capability - await expect(server.sendToolListChanged()).rejects.toThrow('Server does not support notifying of tool list changes'); -}); - -/*** - * Test: Only Allow setRequestHandler for Declared Capabilities - */ -test('should only allow setRequestHandler for declared capabilities', () => { - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - // This should work because sampling is a declared capability - expect(() => { - client.setRequestHandler(CreateMessageRequestSchema, () => ({ - model: 'test-model', - role: 'assistant', - content: { - type: 'text', - text: 'Test response' - } - })); - }).not.toThrow(); - - // This should throw because roots listing is not a declared capability - expect(() => { - client.setRequestHandler(ListRootsRequestSchema, () => ({})); - }).toThrow('Client does not support roots capability'); -}); - -test('should allow setRequestHandler for declared elicitation capability', () => { - const client = new Client( - { - name: 'test-client', - version: '1.0.0' - }, - { - capabilities: { - elicitation: {} - } - } - ); - - // This should work because elicitation is a declared capability - expect(() => { - client.setRequestHandler(ElicitRequestSchema, () => ({ - action: 'accept', - content: { - username: 'test-user', - confirmed: true - } - })); - }).not.toThrow(); - - // This should throw because sampling is not a declared capability - expect(() => { - client.setRequestHandler(CreateMessageRequestSchema, () => ({ - model: 'test-model', - role: 'assistant', - content: { - type: 'text', - text: 'Test response' - } - })); - }).toThrow('Client does not support sampling capability'); -}); - -/*** - * Test: Type Checking - * Test that custom request/notification/result schemas can be used with the Client class. - */ -test('should typecheck', () => { - const GetWeatherRequestSchema = RequestSchema.extend({ - method: z.literal('weather/get'), - params: z.object({ - city: z.string() - }) - }); - - const GetForecastRequestSchema = RequestSchema.extend({ - method: z.literal('weather/forecast'), - params: z.object({ - city: z.string(), - days: z.number() - }) - }); - - const WeatherForecastNotificationSchema = NotificationSchema.extend({ - method: z.literal('weather/alert'), - params: z.object({ - severity: z.enum(['warning', 'watch']), - message: z.string() - }) - }); - - const WeatherRequestSchema = GetWeatherRequestSchema.or(GetForecastRequestSchema); - const WeatherNotificationSchema = WeatherForecastNotificationSchema; - const WeatherResultSchema = ResultSchema.extend({ - temperature: z.number(), - conditions: z.string() - }); - - type WeatherRequest = z.infer; - type WeatherNotification = z.infer; - type WeatherResult = z.infer; - - // Create a typed Client for weather data - const weatherClient = new Client( - { - name: 'WeatherClient', - version: '1.0.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - // Typecheck that only valid weather requests/notifications/results are allowed - false && - weatherClient.request( - { - method: 'weather/get', - params: { - city: 'Seattle' - } - }, - WeatherResultSchema - ); - - false && - weatherClient.notification({ - method: 'weather/alert', - params: { - severity: 'warning', - message: 'Storm approaching' - } - }); -}); - -/*** - * Test: Handle Client Cancelling a Request - */ -test('should handle client cancelling a request', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - resources: {} - } - } - ); - - // Set up server to delay responding to listResources - server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { - await new Promise(resolve => setTimeout(resolve, 1000)); - return { - resources: [] - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: {} - } - ); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // Set up abort controller - const controller = new AbortController(); - - // Issue request but cancel it immediately - const listResourcesPromise = client.listResources(undefined, { - signal: controller.signal - }); - controller.abort('Cancelled by test'); - - // Request should be rejected - await expect(listResourcesPromise).rejects.toBe('Cancelled by test'); -}); - -/*** - * Test: Handle Request Timeout - */ -test('should handle request timeout', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - resources: {} - } - } - ); - - // Set up server with a delayed response - server.setRequestHandler(ListResourcesRequestSchema, async (_request, extra) => { - const timer = new Promise(resolve => { - const timeout = setTimeout(resolve, 100); - extra.signal.addEventListener('abort', () => clearTimeout(timeout)); - }); - - await timer; - return { - resources: [] - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: {} - } - ); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // Request with 0 msec timeout should fail immediately - await expect(client.listResources(undefined, { timeout: 0 })).rejects.toMatchObject({ - code: ErrorCode.RequestTimeout - }); -}); - -describe('outputSchema validation', () => { - /*** - * Test: Validate structuredContent Against outputSchema - */ - test('should validate structuredContent against outputSchema', async () => { - const server = new Server( - { - name: 'test-server', - version: '1.0.0' - }, - { - capabilities: { - tools: {} - } - } - ); - - // Set up server handlers - server.setRequestHandler(InitializeRequestSchema, async request => ({ - protocolVersion: request.params.protocolVersion, - capabilities: {}, - serverInfo: { - name: 'test-server', - version: '1.0.0' - } - })); - - server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [ - { - name: 'test-tool', - description: 'A test tool', - inputSchema: { - type: 'object', - properties: {} - }, - outputSchema: { - type: 'object', - properties: { - result: { type: 'string' }, - count: { type: 'number' } - }, - required: ['result', 'count'], - additionalProperties: false - } - } - ] - })); - - server.setRequestHandler(CallToolRequestSchema, async request => { - if (request.params.name === 'test-tool') { - return { - structuredContent: { result: 'success', count: 42 } - }; - } - throw new Error('Unknown tool'); - }); - - const client = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // List tools to cache the schemas - await client.listTools(); - - // Call the tool - should validate successfully - const result = await client.callTool({ name: 'test-tool' }); - expect(result.structuredContent).toEqual({ result: 'success', count: 42 }); - }); - - /*** - * Test: Throw Error when structuredContent Does Not Match Schema - */ - test('should throw error when structuredContent does not match schema', async () => { - const server = new Server( - { - name: 'test-server', - version: '1.0.0' - }, - { - capabilities: { - tools: {} - } - } - ); - - // Set up server handlers - server.setRequestHandler(InitializeRequestSchema, async request => ({ - protocolVersion: request.params.protocolVersion, - capabilities: {}, - serverInfo: { - name: 'test-server', - version: '1.0.0' - } - })); - - server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [ - { - name: 'test-tool', - description: 'A test tool', - inputSchema: { - type: 'object', - properties: {} - }, - outputSchema: { - type: 'object', - properties: { - result: { type: 'string' }, - count: { type: 'number' } - }, - required: ['result', 'count'], - additionalProperties: false - } - } - ] - })); - - server.setRequestHandler(CallToolRequestSchema, async request => { - if (request.params.name === 'test-tool') { - // Return invalid structured content (count is string instead of number) - return { - structuredContent: { result: 'success', count: 'not a number' } - }; - } - throw new Error('Unknown tool'); - }); - - const client = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // List tools to cache the schemas - await client.listTools(); - - // Call the tool - should throw validation error - await expect(client.callTool({ name: 'test-tool' })).rejects.toThrow(/Structured content does not match the tool's output schema/); - }); - - /*** - * Test: Throw Error when Tool with outputSchema Returns No structuredContent - */ - test('should throw error when tool with outputSchema returns no structuredContent', async () => { - const server = new Server( - { - name: 'test-server', - version: '1.0.0' - }, - { - capabilities: { - tools: {} - } - } - ); - - // Set up server handlers - server.setRequestHandler(InitializeRequestSchema, async request => ({ - protocolVersion: request.params.protocolVersion, - capabilities: {}, - serverInfo: { - name: 'test-server', - version: '1.0.0' - } - })); - - server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [ - { - name: 'test-tool', - description: 'A test tool', - inputSchema: { - type: 'object', - properties: {} - }, - outputSchema: { - type: 'object', - properties: { - result: { type: 'string' } - }, - required: ['result'] - } - } - ] - })); - - server.setRequestHandler(CallToolRequestSchema, async request => { - if (request.params.name === 'test-tool') { - // Return content instead of structuredContent - return { - content: [{ type: 'text', text: 'This should be structured content' }] - }; - } - throw new Error('Unknown tool'); - }); - - const client = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // List tools to cache the schemas - await client.listTools(); - - // Call the tool - should throw error - await expect(client.callTool({ name: 'test-tool' })).rejects.toThrow( - /Tool test-tool has an output schema but did not return structured content/ - ); - }); - - /*** - * Test: Handle Tools Without outputSchema Normally - */ - test('should handle tools without outputSchema normally', async () => { - const server = new Server( - { - name: 'test-server', - version: '1.0.0' - }, - { - capabilities: { - tools: {} - } - } - ); - - // Set up server handlers - server.setRequestHandler(InitializeRequestSchema, async request => ({ - protocolVersion: request.params.protocolVersion, - capabilities: {}, - serverInfo: { - name: 'test-server', - version: '1.0.0' - } - })); - - server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [ - { - name: 'test-tool', - description: 'A test tool', - inputSchema: { - type: 'object', - properties: {} - } - // No outputSchema - } - ] - })); - - server.setRequestHandler(CallToolRequestSchema, async request => { - if (request.params.name === 'test-tool') { - // Return regular content - return { - content: [{ type: 'text', text: 'Normal response' }] - }; - } - throw new Error('Unknown tool'); - }); - - const client = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // List tools to cache the schemas - await client.listTools(); - - // Call the tool - should work normally without validation - const result = await client.callTool({ name: 'test-tool' }); - expect(result.content).toEqual([{ type: 'text', text: 'Normal response' }]); - }); - - /*** - * Test: Handle Complex JSON Schema Validation - */ - test('should handle complex JSON schema validation', async () => { - const server = new Server( - { - name: 'test-server', - version: '1.0.0' - }, - { - capabilities: { - tools: {} - } - } - ); - - // Set up server handlers - server.setRequestHandler(InitializeRequestSchema, async request => ({ - protocolVersion: request.params.protocolVersion, - capabilities: {}, - serverInfo: { - name: 'test-server', - version: '1.0.0' - } - })); - - server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [ - { - name: 'complex-tool', - description: 'A tool with complex schema', - inputSchema: { - type: 'object', - properties: {} - }, - outputSchema: { - type: 'object', - properties: { - name: { type: 'string', minLength: 3 }, - age: { type: 'integer', minimum: 0, maximum: 120 }, - active: { type: 'boolean' }, - tags: { - type: 'array', - items: { type: 'string' }, - minItems: 1 - }, - metadata: { - type: 'object', - properties: { - created: { type: 'string' } - }, - required: ['created'] - } - }, - required: ['name', 'age', 'active', 'tags', 'metadata'], - additionalProperties: false - } - } - ] - })); - - server.setRequestHandler(CallToolRequestSchema, async request => { - if (request.params.name === 'complex-tool') { - return { - structuredContent: { - name: 'John Doe', - age: 30, - active: true, - tags: ['user', 'admin'], - metadata: { - created: '2023-01-01T00:00:00Z' - } - } - }; - } - throw new Error('Unknown tool'); - }); - - const client = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // List tools to cache the schemas - await client.listTools(); - - // Call the tool - should validate successfully - const result = await client.callTool({ name: 'complex-tool' }); - expect(result.structuredContent).toBeDefined(); - const structuredContent = result.structuredContent as { name: string; age: number }; - expect(structuredContent.name).toBe('John Doe'); - expect(structuredContent.age).toBe(30); - }); - - /*** - * Test: Fail Validation with Additional Properties When Not Allowed - */ - test('should fail validation with additional properties when not allowed', async () => { - const server = new Server( - { - name: 'test-server', - version: '1.0.0' - }, - { - capabilities: { - tools: {} - } - } - ); - - // Set up server handlers - server.setRequestHandler(InitializeRequestSchema, async request => ({ - protocolVersion: request.params.protocolVersion, - capabilities: {}, - serverInfo: { - name: 'test-server', - version: '1.0.0' - } - })); - - server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [ - { - name: 'strict-tool', - description: 'A tool with strict schema', - inputSchema: { - type: 'object', - properties: {} - }, - outputSchema: { - type: 'object', - properties: { - name: { type: 'string' } - }, - required: ['name'], - additionalProperties: false - } - } - ] - })); - - server.setRequestHandler(CallToolRequestSchema, async request => { - if (request.params.name === 'strict-tool') { - // Return structured content with extra property - return { - structuredContent: { - name: 'John', - extraField: 'not allowed' - } - }; - } - throw new Error('Unknown tool'); - }); - - const client = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // List tools to cache the schemas - await client.listTools(); - - // Call the tool - should throw validation error due to additional property - await expect(client.callTool({ name: 'strict-tool' })).rejects.toThrow( - /Structured content does not match the tool's output schema/ - ); - }); -}); diff --git a/typescript-sdk/src/client/index.ts b/typescript-sdk/src/client/index.ts deleted file mode 100644 index cc68198..0000000 --- a/typescript-sdk/src/client/index.ts +++ /dev/null @@ -1,440 +0,0 @@ -import { mergeCapabilities, Protocol, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; -import type { Transport } from '../shared/transport.js'; -import { - type CallToolRequest, - CallToolResultSchema, - type ClientCapabilities, - type ClientNotification, - type ClientRequest, - type ClientResult, - type CompatibilityCallToolResultSchema, - type CompleteRequest, - CompleteResultSchema, - EmptyResultSchema, - ErrorCode, - type GetPromptRequest, - GetPromptResultSchema, - type Implementation, - InitializeResultSchema, - LATEST_PROTOCOL_VERSION, - type ListPromptsRequest, - ListPromptsResultSchema, - type ListResourcesRequest, - ListResourcesResultSchema, - type ListResourceTemplatesRequest, - ListResourceTemplatesResultSchema, - type ListToolsRequest, - ListToolsResultSchema, - type LoggingLevel, - McpError, - type Notification, - type ReadResourceRequest, - ReadResourceResultSchema, - type Request, - type Result, - type ServerCapabilities, - SUPPORTED_PROTOCOL_VERSIONS, - type SubscribeRequest, - type Tool, - type UnsubscribeRequest -} from '../types.js'; -import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; -import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from '../validation/types.js'; - -export type ClientOptions = ProtocolOptions & { - /** - * Capabilities to advertise as being supported by this client. - */ - capabilities?: ClientCapabilities; - - /** - * JSON Schema validator for tool output validation. - * - * The validator is used to validate structured content returned by tools - * against their declared output schemas. - * - * @default AjvJsonSchemaValidator - * - * @example - * ```typescript - * // ajv - * const client = new Client( - * { name: 'my-client', version: '1.0.0' }, - * { - * capabilities: {}, - * jsonSchemaValidator: new AjvJsonSchemaValidator() - * } - * ); - * - * // @cfworker/json-schema - * const client = new Client( - * { name: 'my-client', version: '1.0.0' }, - * { - * capabilities: {}, - * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() - * } - * ); - * ``` - */ - jsonSchemaValidator?: jsonSchemaValidator; -}; - -/** - * An MCP client on top of a pluggable transport. - * - * The client will automatically begin the initialization flow with the server when connect() is called. - * - * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: - * - * ```typescript - * // Custom schemas - * const CustomRequestSchema = RequestSchema.extend({...}) - * const CustomNotificationSchema = NotificationSchema.extend({...}) - * const CustomResultSchema = ResultSchema.extend({...}) - * - * // Type aliases - * type CustomRequest = z.infer - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed client - * const client = new Client({ - * name: "CustomClient", - * version: "1.0.0" - * }) - * ``` - */ -export class Client< - RequestT extends Request = Request, - NotificationT extends Notification = Notification, - ResultT extends Result = Result -> extends Protocol { - private _serverCapabilities?: ServerCapabilities; - private _serverVersion?: Implementation; - private _capabilities: ClientCapabilities; - private _instructions?: string; - private _jsonSchemaValidator: jsonSchemaValidator; - private _cachedToolOutputValidators: Map> = new Map(); - - /** - * Initializes this client with the given name and version information. - */ - constructor( - private _clientInfo: Implementation, - options?: ClientOptions - ) { - super(options); - this._capabilities = options?.capabilities ?? {}; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - } - - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - public registerCapabilities(capabilities: ClientCapabilities): void { - if (this.transport) { - throw new Error('Cannot register capabilities after connecting to transport'); - } - - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - } - - protected assertCapability(capability: keyof ServerCapabilities, method: string): void { - if (!this._serverCapabilities?.[capability]) { - throw new Error(`Server does not support ${capability} (required for ${method})`); - } - } - - override async connect(transport: Transport, options?: RequestOptions): Promise { - await super.connect(transport); - // When transport sessionId is already set this means we are trying to reconnect. - // In this case we don't need to initialize again. - if (transport.sessionId !== undefined) { - return; - } - try { - const result = await this.request( - { - method: 'initialize', - params: { - protocolVersion: LATEST_PROTOCOL_VERSION, - capabilities: this._capabilities, - clientInfo: this._clientInfo - } - }, - InitializeResultSchema, - options - ); - - if (result === undefined) { - throw new Error(`Server sent invalid initialize result: ${result}`); - } - - if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) { - throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); - } - - this._serverCapabilities = result.capabilities; - this._serverVersion = result.serverInfo; - // HTTP transports must set the protocol version in each header after initialization. - if (transport.setProtocolVersion) { - transport.setProtocolVersion(result.protocolVersion); - } - - this._instructions = result.instructions; - - await this.notification({ - method: 'notifications/initialized' - }); - } catch (error) { - // Disconnect if initialization fails. - void this.close(); - throw error; - } - } - - /** - * After initialization has completed, this will be populated with the server's reported capabilities. - */ - getServerCapabilities(): ServerCapabilities | undefined { - return this._serverCapabilities; - } - - /** - * After initialization has completed, this will be populated with information about the server's name and version. - */ - getServerVersion(): Implementation | undefined { - return this._serverVersion; - } - - /** - * After initialization has completed, this may be populated with information about the server's instructions. - */ - getInstructions(): string | undefined { - return this._instructions; - } - - protected assertCapabilityForMethod(method: RequestT['method']): void { - switch (method as ClientRequest['method']) { - case 'logging/setLevel': - if (!this._serverCapabilities?.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - - case 'prompts/get': - case 'prompts/list': - if (!this._serverCapabilities?.prompts) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - - case 'resources/list': - case 'resources/templates/list': - case 'resources/read': - case 'resources/subscribe': - case 'resources/unsubscribe': - if (!this._serverCapabilities?.resources) { - throw new Error(`Server does not support resources (required for ${method})`); - } - - if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) { - throw new Error(`Server does not support resource subscriptions (required for ${method})`); - } - - break; - - case 'tools/call': - case 'tools/list': - if (!this._serverCapabilities?.tools) { - throw new Error(`Server does not support tools (required for ${method})`); - } - break; - - case 'completion/complete': - if (!this._serverCapabilities?.completions) { - throw new Error(`Server does not support completions (required for ${method})`); - } - break; - - case 'initialize': - // No specific capability required for initialize - break; - - case 'ping': - // No specific capability required for ping - break; - } - } - - protected assertNotificationCapability(method: NotificationT['method']): void { - switch (method as ClientNotification['method']) { - case 'notifications/roots/list_changed': - if (!this._capabilities.roots?.listChanged) { - throw new Error(`Client does not support roots list changed notifications (required for ${method})`); - } - break; - - case 'notifications/initialized': - // No specific capability required for initialized - break; - - case 'notifications/cancelled': - // Cancellation notifications are always allowed - break; - - case 'notifications/progress': - // Progress notifications are always allowed - break; - } - } - - protected assertRequestHandlerCapability(method: string): void { - switch (method) { - case 'sampling/createMessage': - if (!this._capabilities.sampling) { - throw new Error(`Client does not support sampling capability (required for ${method})`); - } - break; - - case 'elicitation/create': - if (!this._capabilities.elicitation) { - throw new Error(`Client does not support elicitation capability (required for ${method})`); - } - break; - - case 'roots/list': - if (!this._capabilities.roots) { - throw new Error(`Client does not support roots capability (required for ${method})`); - } - break; - - case 'ping': - // No specific capability required for ping - break; - } - } - - async ping(options?: RequestOptions) { - return this.request({ method: 'ping' }, EmptyResultSchema, options); - } - - async complete(params: CompleteRequest['params'], options?: RequestOptions) { - return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options); - } - - async setLoggingLevel(level: LoggingLevel, options?: RequestOptions) { - return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options); - } - - async getPrompt(params: GetPromptRequest['params'], options?: RequestOptions) { - return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options); - } - - async listPrompts(params?: ListPromptsRequest['params'], options?: RequestOptions) { - return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options); - } - - async listResources(params?: ListResourcesRequest['params'], options?: RequestOptions) { - return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options); - } - - async listResourceTemplates(params?: ListResourceTemplatesRequest['params'], options?: RequestOptions) { - return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options); - } - - async readResource(params: ReadResourceRequest['params'], options?: RequestOptions) { - return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options); - } - - async subscribeResource(params: SubscribeRequest['params'], options?: RequestOptions) { - return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options); - } - - async unsubscribeResource(params: UnsubscribeRequest['params'], options?: RequestOptions) { - return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options); - } - - async callTool( - params: CallToolRequest['params'], - resultSchema: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema = CallToolResultSchema, - options?: RequestOptions - ) { - const result = await this.request({ method: 'tools/call', params }, resultSchema, options); - - // Check if the tool has an outputSchema - const validator = this.getToolOutputValidator(params.name); - if (validator) { - // If tool has outputSchema, it MUST return structuredContent (unless it's an error) - if (!result.structuredContent && !result.isError) { - throw new McpError( - ErrorCode.InvalidRequest, - `Tool ${params.name} has an output schema but did not return structured content` - ); - } - - // Only validate structured content if present (not when there's an error) - if (result.structuredContent) { - try { - // Validate the structured content against the schema - const validationResult = validator(result.structuredContent); - - if (!validationResult.valid) { - throw new McpError( - ErrorCode.InvalidParams, - `Structured content does not match the tool's output schema: ${validationResult.errorMessage}` - ); - } - } catch (error) { - if (error instanceof McpError) { - throw error; - } - throw new McpError( - ErrorCode.InvalidParams, - `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}` - ); - } - } - } - - return result; - } - - /** - * Cache validators for tool output schemas. - * Called after listTools() to pre-compile validators for better performance. - */ - private cacheToolOutputSchemas(tools: Tool[]): void { - this._cachedToolOutputValidators.clear(); - - for (const tool of tools) { - // If the tool has an outputSchema, create and cache the validator - if (tool.outputSchema) { - const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema as JsonSchemaType); - this._cachedToolOutputValidators.set(tool.name, toolValidator); - } - } - } - - /** - * Get cached validator for a tool - */ - private getToolOutputValidator(toolName: string): JsonSchemaValidator | undefined { - return this._cachedToolOutputValidators.get(toolName); - } - - async listTools(params?: ListToolsRequest['params'], options?: RequestOptions) { - const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options); - - // Cache the tools and their output schemas for future validation - this.cacheToolOutputSchemas(result.tools); - - return result; - } - - async sendRootsListChanged() { - return this.notification({ method: 'notifications/roots/list_changed' }); - } -} diff --git a/typescript-sdk/src/client/middleware.test.ts b/typescript-sdk/src/client/middleware.test.ts deleted file mode 100644 index c042051..0000000 --- a/typescript-sdk/src/client/middleware.test.ts +++ /dev/null @@ -1,1105 +0,0 @@ -import { withOAuth, withLogging, applyMiddlewares, createMiddleware } from './middleware.js'; -import { OAuthClientProvider } from './auth.js'; -import { FetchLike } from '../shared/transport.js'; - -jest.mock('../client/auth.js', () => { - const actual = jest.requireActual('../client/auth.js'); - return { - ...actual, - auth: jest.fn(), - extractResourceMetadataUrl: jest.fn() - }; -}); - -import { auth, extractResourceMetadataUrl } from './auth.js'; - -const mockAuth = auth as jest.MockedFunction; -const mockExtractResourceMetadataUrl = extractResourceMetadataUrl as jest.MockedFunction; - -describe('withOAuth', () => { - let mockProvider: jest.Mocked; - let mockFetch: jest.MockedFunction; - - beforeEach(() => { - jest.clearAllMocks(); - - mockProvider = { - get redirectUrl() { - return 'http://localhost/callback'; - }, - get clientMetadata() { - return { redirect_uris: ['http://localhost/callback'] }; - }, - tokens: jest.fn(), - saveTokens: jest.fn(), - clientInformation: jest.fn(), - redirectToAuthorization: jest.fn(), - saveCodeVerifier: jest.fn(), - codeVerifier: jest.fn(), - invalidateCredentials: jest.fn() - }; - - mockFetch = jest.fn(); - }); - - it('should add Authorization header when tokens are available (with explicit baseUrl)', async () => { - mockProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - mockFetch.mockResolvedValue(new Response('success', { status: 200 })); - - const enhancedFetch = withOAuth(mockProvider, 'https://api.example.com')(mockFetch); - - await enhancedFetch('https://api.example.com/data'); - - expect(mockFetch).toHaveBeenCalledWith( - 'https://api.example.com/data', - expect.objectContaining({ - headers: expect.any(Headers) - }) - ); - - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('Authorization')).toBe('Bearer test-token'); - }); - - it('should add Authorization header when tokens are available (without baseUrl)', async () => { - mockProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - mockFetch.mockResolvedValue(new Response('success', { status: 200 })); - - // Test without baseUrl - should extract from request URL - const enhancedFetch = withOAuth(mockProvider)(mockFetch); - - await enhancedFetch('https://api.example.com/data'); - - expect(mockFetch).toHaveBeenCalledWith( - 'https://api.example.com/data', - expect.objectContaining({ - headers: expect.any(Headers) - }) - ); - - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('Authorization')).toBe('Bearer test-token'); - }); - - it('should handle requests without tokens (without baseUrl)', async () => { - mockProvider.tokens.mockResolvedValue(undefined); - mockFetch.mockResolvedValue(new Response('success', { status: 200 })); - - // Test without baseUrl - const enhancedFetch = withOAuth(mockProvider)(mockFetch); - - await enhancedFetch('https://api.example.com/data'); - - expect(mockFetch).toHaveBeenCalledTimes(1); - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('Authorization')).toBeNull(); - }); - - it('should retry request after successful auth on 401 response (with explicit baseUrl)', async () => { - mockProvider.tokens - .mockResolvedValueOnce({ - access_token: 'old-token', - token_type: 'Bearer', - expires_in: 3600 - }) - .mockResolvedValueOnce({ - access_token: 'new-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - const unauthorizedResponse = new Response('Unauthorized', { - status: 401, - headers: { 'www-authenticate': 'Bearer realm="oauth"' } - }); - const successResponse = new Response('success', { status: 200 }); - - mockFetch.mockResolvedValueOnce(unauthorizedResponse).mockResolvedValueOnce(successResponse); - - const mockResourceUrl = new URL('https://oauth.example.com/.well-known/oauth-protected-resource'); - mockExtractResourceMetadataUrl.mockReturnValue(mockResourceUrl); - mockAuth.mockResolvedValue('AUTHORIZED'); - - const enhancedFetch = withOAuth(mockProvider, 'https://api.example.com')(mockFetch); - - const result = await enhancedFetch('https://api.example.com/data'); - - expect(result).toBe(successResponse); - expect(mockFetch).toHaveBeenCalledTimes(2); - expect(mockAuth).toHaveBeenCalledWith(mockProvider, { - serverUrl: 'https://api.example.com', - resourceMetadataUrl: mockResourceUrl, - fetchFn: mockFetch - }); - - // Verify the retry used the new token - const retryCallArgs = mockFetch.mock.calls[1]; - const retryHeaders = retryCallArgs[1]?.headers as Headers; - expect(retryHeaders.get('Authorization')).toBe('Bearer new-token'); - }); - - it('should retry request after successful auth on 401 response (without baseUrl)', async () => { - mockProvider.tokens - .mockResolvedValueOnce({ - access_token: 'old-token', - token_type: 'Bearer', - expires_in: 3600 - }) - .mockResolvedValueOnce({ - access_token: 'new-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - const unauthorizedResponse = new Response('Unauthorized', { - status: 401, - headers: { 'www-authenticate': 'Bearer realm="oauth"' } - }); - const successResponse = new Response('success', { status: 200 }); - - mockFetch.mockResolvedValueOnce(unauthorizedResponse).mockResolvedValueOnce(successResponse); - - const mockResourceUrl = new URL('https://oauth.example.com/.well-known/oauth-protected-resource'); - mockExtractResourceMetadataUrl.mockReturnValue(mockResourceUrl); - mockAuth.mockResolvedValue('AUTHORIZED'); - - // Test without baseUrl - should extract from request URL - const enhancedFetch = withOAuth(mockProvider)(mockFetch); - - const result = await enhancedFetch('https://api.example.com/data'); - - expect(result).toBe(successResponse); - expect(mockFetch).toHaveBeenCalledTimes(2); - expect(mockAuth).toHaveBeenCalledWith(mockProvider, { - serverUrl: 'https://api.example.com', // Should be extracted from request URL - resourceMetadataUrl: mockResourceUrl, - fetchFn: mockFetch - }); - - // Verify the retry used the new token - const retryCallArgs = mockFetch.mock.calls[1]; - const retryHeaders = retryCallArgs[1]?.headers as Headers; - expect(retryHeaders.get('Authorization')).toBe('Bearer new-token'); - }); - - it('should throw UnauthorizedError when auth returns REDIRECT (without baseUrl)', async () => { - mockProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - mockFetch.mockResolvedValue(new Response('Unauthorized', { status: 401 })); - mockExtractResourceMetadataUrl.mockReturnValue(undefined); - mockAuth.mockResolvedValue('REDIRECT'); - - // Test without baseUrl - const enhancedFetch = withOAuth(mockProvider)(mockFetch); - - await expect(enhancedFetch('https://api.example.com/data')).rejects.toThrow( - 'Authentication requires user authorization - redirect initiated' - ); - }); - - it('should throw UnauthorizedError when auth fails', async () => { - mockProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - mockFetch.mockResolvedValue(new Response('Unauthorized', { status: 401 })); - mockExtractResourceMetadataUrl.mockReturnValue(undefined); - mockAuth.mockRejectedValue(new Error('Network error')); - - const enhancedFetch = withOAuth(mockProvider, 'https://api.example.com')(mockFetch); - - await expect(enhancedFetch('https://api.example.com/data')).rejects.toThrow('Failed to re-authenticate: Network error'); - }); - - it('should handle persistent 401 responses after auth', async () => { - mockProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - // Always return 401 - mockFetch.mockResolvedValue(new Response('Unauthorized', { status: 401 })); - mockExtractResourceMetadataUrl.mockReturnValue(undefined); - mockAuth.mockResolvedValue('AUTHORIZED'); - - const enhancedFetch = withOAuth(mockProvider, 'https://api.example.com')(mockFetch); - - await expect(enhancedFetch('https://api.example.com/data')).rejects.toThrow( - 'Authentication failed for https://api.example.com/data' - ); - - // Should have made initial request + 1 retry after auth = 2 total - expect(mockFetch).toHaveBeenCalledTimes(2); - expect(mockAuth).toHaveBeenCalledTimes(1); - }); - - it('should preserve original request method and body', async () => { - mockProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - mockFetch.mockResolvedValue(new Response('success', { status: 200 })); - - const enhancedFetch = withOAuth(mockProvider, 'https://api.example.com')(mockFetch); - - const requestBody = JSON.stringify({ data: 'test' }); - await enhancedFetch('https://api.example.com/data', { - method: 'POST', - body: requestBody, - headers: { 'Content-Type': 'application/json' } - }); - - expect(mockFetch).toHaveBeenCalledWith( - 'https://api.example.com/data', - expect.objectContaining({ - method: 'POST', - body: requestBody, - headers: expect.any(Headers) - }) - ); - - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('Content-Type')).toBe('application/json'); - expect(headers.get('Authorization')).toBe('Bearer test-token'); - }); - - it('should handle non-401 errors normally', async () => { - mockProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - const serverErrorResponse = new Response('Server Error', { status: 500 }); - mockFetch.mockResolvedValue(serverErrorResponse); - - const enhancedFetch = withOAuth(mockProvider, 'https://api.example.com')(mockFetch); - - const result = await enhancedFetch('https://api.example.com/data'); - - expect(result).toBe(serverErrorResponse); - expect(mockFetch).toHaveBeenCalledTimes(1); - expect(mockAuth).not.toHaveBeenCalled(); - }); - - it('should handle URL object as input (without baseUrl)', async () => { - mockProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - mockFetch.mockResolvedValue(new Response('success', { status: 200 })); - - // Test URL object without baseUrl - should extract origin from URL object - const enhancedFetch = withOAuth(mockProvider)(mockFetch); - - await enhancedFetch(new URL('https://api.example.com/data')); - - expect(mockFetch).toHaveBeenCalledWith( - expect.any(URL), - expect.objectContaining({ - headers: expect.any(Headers) - }) - ); - }); - - it('should handle URL object in auth retry (without baseUrl)', async () => { - mockProvider.tokens - .mockResolvedValueOnce({ - access_token: 'old-token', - token_type: 'Bearer', - expires_in: 3600 - }) - .mockResolvedValueOnce({ - access_token: 'new-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - const unauthorizedResponse = new Response('Unauthorized', { status: 401 }); - const successResponse = new Response('success', { status: 200 }); - - mockFetch.mockResolvedValueOnce(unauthorizedResponse).mockResolvedValueOnce(successResponse); - - mockExtractResourceMetadataUrl.mockReturnValue(undefined); - mockAuth.mockResolvedValue('AUTHORIZED'); - - const enhancedFetch = withOAuth(mockProvider)(mockFetch); - - const result = await enhancedFetch(new URL('https://api.example.com/data')); - - expect(result).toBe(successResponse); - expect(mockFetch).toHaveBeenCalledTimes(2); - expect(mockAuth).toHaveBeenCalledWith(mockProvider, { - serverUrl: 'https://api.example.com', // Should extract origin from URL object - resourceMetadataUrl: undefined, - fetchFn: mockFetch - }); - }); -}); - -describe('withLogging', () => { - let mockFetch: jest.MockedFunction; - let mockLogger: jest.MockedFunction< - (input: { - method: string; - url: string | URL; - status: number; - statusText: string; - duration: number; - requestHeaders?: Headers; - responseHeaders?: Headers; - error?: Error; - }) => void - >; - let consoleErrorSpy: jest.SpyInstance; - let consoleLogSpy: jest.SpyInstance; - - beforeEach(() => { - jest.clearAllMocks(); - - consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); - consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => {}); - - mockFetch = jest.fn(); - mockLogger = jest.fn(); - }); - - afterEach(() => { - consoleErrorSpy.mockRestore(); - consoleLogSpy.mockRestore(); - }); - - it('should log successful requests with default logger', async () => { - const response = new Response('success', { status: 200, statusText: 'OK' }); - mockFetch.mockResolvedValue(response); - - const enhancedFetch = withLogging()(mockFetch); - - await enhancedFetch('https://api.example.com/data'); - - expect(consoleLogSpy).toHaveBeenCalledWith( - expect.stringMatching(/HTTP GET https:\/\/api\.example\.com\/data 200 OK \(\d+\.\d+ms\)/) - ); - }); - - it('should log error responses with default logger', async () => { - const response = new Response('Not Found', { - status: 404, - statusText: 'Not Found' - }); - mockFetch.mockResolvedValue(response); - - const enhancedFetch = withLogging()(mockFetch); - - await enhancedFetch('https://api.example.com/data'); - - expect(consoleErrorSpy).toHaveBeenCalledWith( - expect.stringMatching(/HTTP GET https:\/\/api\.example\.com\/data 404 Not Found \(\d+\.\d+ms\)/) - ); - }); - - it('should log network errors with default logger', async () => { - const networkError = new Error('Network connection failed'); - mockFetch.mockRejectedValue(networkError); - - const enhancedFetch = withLogging()(mockFetch); - - await expect(enhancedFetch('https://api.example.com/data')).rejects.toThrow('Network connection failed'); - - expect(consoleErrorSpy).toHaveBeenCalledWith( - expect.stringMatching(/HTTP GET https:\/\/api\.example\.com\/data failed: Network connection failed \(\d+\.\d+ms\)/) - ); - }); - - it('should use custom logger when provided', async () => { - const response = new Response('success', { status: 200, statusText: 'OK' }); - mockFetch.mockResolvedValue(response); - - const enhancedFetch = withLogging({ logger: mockLogger })(mockFetch); - - await enhancedFetch('https://api.example.com/data', { method: 'POST' }); - - expect(mockLogger).toHaveBeenCalledWith({ - method: 'POST', - url: 'https://api.example.com/data', - status: 200, - statusText: 'OK', - duration: expect.any(Number), - requestHeaders: undefined, - responseHeaders: undefined - }); - - expect(consoleLogSpy).not.toHaveBeenCalled(); - }); - - it('should include request headers when configured', async () => { - const response = new Response('success', { status: 200, statusText: 'OK' }); - mockFetch.mockResolvedValue(response); - - const enhancedFetch = withLogging({ - logger: mockLogger, - includeRequestHeaders: true - })(mockFetch); - - await enhancedFetch('https://api.example.com/data', { - headers: { - Authorization: 'Bearer token', - 'Content-Type': 'application/json' - } - }); - - expect(mockLogger).toHaveBeenCalledWith({ - method: 'GET', - url: 'https://api.example.com/data', - status: 200, - statusText: 'OK', - duration: expect.any(Number), - requestHeaders: expect.any(Headers), - responseHeaders: undefined - }); - - const logCall = mockLogger.mock.calls[0][0]; - expect(logCall.requestHeaders?.get('Authorization')).toBe('Bearer token'); - expect(logCall.requestHeaders?.get('Content-Type')).toBe('application/json'); - }); - - it('should include response headers when configured', async () => { - const response = new Response('success', { - status: 200, - statusText: 'OK', - headers: { - 'Content-Type': 'application/json', - 'Cache-Control': 'no-cache' - } - }); - mockFetch.mockResolvedValue(response); - - const enhancedFetch = withLogging({ - logger: mockLogger, - includeResponseHeaders: true - })(mockFetch); - - await enhancedFetch('https://api.example.com/data'); - - const logCall = mockLogger.mock.calls[0][0]; - expect(logCall.responseHeaders?.get('Content-Type')).toBe('application/json'); - expect(logCall.responseHeaders?.get('Cache-Control')).toBe('no-cache'); - }); - - it('should respect statusLevel option', async () => { - const successResponse = new Response('success', { - status: 200, - statusText: 'OK' - }); - const errorResponse = new Response('Server Error', { - status: 500, - statusText: 'Internal Server Error' - }); - - mockFetch.mockResolvedValueOnce(successResponse).mockResolvedValueOnce(errorResponse); - - const enhancedFetch = withLogging({ - logger: mockLogger, - statusLevel: 400 - })(mockFetch); - - // 200 response should not be logged (below statusLevel 400) - await enhancedFetch('https://api.example.com/success'); - expect(mockLogger).not.toHaveBeenCalled(); - - // 500 response should be logged (above statusLevel 400) - await enhancedFetch('https://api.example.com/error'); - expect(mockLogger).toHaveBeenCalledWith({ - method: 'GET', - url: 'https://api.example.com/error', - status: 500, - statusText: 'Internal Server Error', - duration: expect.any(Number), - requestHeaders: undefined, - responseHeaders: undefined - }); - }); - - it('should always log network errors regardless of statusLevel', async () => { - const networkError = new Error('Connection timeout'); - mockFetch.mockRejectedValue(networkError); - - const enhancedFetch = withLogging({ - logger: mockLogger, - statusLevel: 500 // Very high log level - })(mockFetch); - - await expect(enhancedFetch('https://api.example.com/data')).rejects.toThrow('Connection timeout'); - - expect(mockLogger).toHaveBeenCalledWith({ - method: 'GET', - url: 'https://api.example.com/data', - status: 0, - statusText: 'Network Error', - duration: expect.any(Number), - requestHeaders: undefined, - error: networkError - }); - }); - - it('should include headers in default logger message when configured', async () => { - const response = new Response('success', { - status: 200, - statusText: 'OK', - headers: { 'Content-Type': 'application/json' } - }); - mockFetch.mockResolvedValue(response); - - const enhancedFetch = withLogging({ - includeRequestHeaders: true, - includeResponseHeaders: true - })(mockFetch); - - await enhancedFetch('https://api.example.com/data', { - headers: { Authorization: 'Bearer token' } - }); - - expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Request Headers: {authorization: Bearer token}')); - expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Response Headers: {content-type: application/json}')); - }); - - it('should measure request duration accurately', async () => { - // Mock a slow response - const response = new Response('success', { status: 200 }); - mockFetch.mockImplementation(async () => { - await new Promise(resolve => setTimeout(resolve, 100)); - return response; - }); - - const enhancedFetch = withLogging({ logger: mockLogger })(mockFetch); - - await enhancedFetch('https://api.example.com/data'); - - const logCall = mockLogger.mock.calls[0][0]; - expect(logCall.duration).toBeGreaterThanOrEqual(90); // Allow some margin for timing - }); -}); - -describe('applyMiddleware', () => { - let mockFetch: jest.MockedFunction; - - beforeEach(() => { - jest.clearAllMocks(); - mockFetch = jest.fn(); - }); - - it('should compose no middleware correctly', () => { - const response = new Response('success', { status: 200 }); - mockFetch.mockResolvedValue(response); - - const composedFetch = applyMiddlewares()(mockFetch); - - expect(composedFetch).toBe(mockFetch); - }); - - it('should compose single middleware correctly', async () => { - const response = new Response('success', { status: 200 }); - mockFetch.mockResolvedValue(response); - - // Create a middleware that adds a header - const middleware1 = (next: FetchLike) => async (input: string | URL, init?: RequestInit) => { - const headers = new Headers(init?.headers); - headers.set('X-Middleware-1', 'applied'); - return next(input, { ...init, headers }); - }; - - const composedFetch = applyMiddlewares(middleware1)(mockFetch); - - await composedFetch('https://api.example.com/data'); - - expect(mockFetch).toHaveBeenCalledWith( - 'https://api.example.com/data', - expect.objectContaining({ - headers: expect.any(Headers) - }) - ); - - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('X-Middleware-1')).toBe('applied'); - }); - - it('should compose multiple middleware in order', async () => { - const response = new Response('success', { status: 200 }); - mockFetch.mockResolvedValue(response); - - // Create middleware that add identifying headers - const middleware1 = (next: FetchLike) => async (input: string | URL, init?: RequestInit) => { - const headers = new Headers(init?.headers); - headers.set('X-Middleware-1', 'applied'); - return next(input, { ...init, headers }); - }; - - const middleware2 = (next: FetchLike) => async (input: string | URL, init?: RequestInit) => { - const headers = new Headers(init?.headers); - headers.set('X-Middleware-2', 'applied'); - return next(input, { ...init, headers }); - }; - - const middleware3 = (next: FetchLike) => async (input: string | URL, init?: RequestInit) => { - const headers = new Headers(init?.headers); - headers.set('X-Middleware-3', 'applied'); - return next(input, { ...init, headers }); - }; - - const composedFetch = applyMiddlewares(middleware1, middleware2, middleware3)(mockFetch); - - await composedFetch('https://api.example.com/data'); - - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('X-Middleware-1')).toBe('applied'); - expect(headers.get('X-Middleware-2')).toBe('applied'); - expect(headers.get('X-Middleware-3')).toBe('applied'); - }); - - it('should work with real fetch middleware functions', async () => { - const response = new Response('success', { status: 200, statusText: 'OK' }); - mockFetch.mockResolvedValue(response); - - // Create middleware that add identifying headers - const oauthMiddleware = (next: FetchLike) => async (input: string | URL, init?: RequestInit) => { - const headers = new Headers(init?.headers); - headers.set('Authorization', 'Bearer test-token'); - return next(input, { ...init, headers }); - }; - - // Use custom logger to avoid console output - const mockLogger = jest.fn(); - const composedFetch = applyMiddlewares(oauthMiddleware, withLogging({ logger: mockLogger, statusLevel: 0 }))(mockFetch); - - await composedFetch('https://api.example.com/data'); - - // Should have both Authorization header and logging - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('Authorization')).toBe('Bearer test-token'); - expect(mockLogger).toHaveBeenCalledWith({ - method: 'GET', - url: 'https://api.example.com/data', - status: 200, - statusText: 'OK', - duration: expect.any(Number), - requestHeaders: undefined, - responseHeaders: undefined - }); - }); - - it('should preserve error propagation through middleware', async () => { - const errorMiddleware = (next: FetchLike) => async (input: string | URL, init?: RequestInit) => { - try { - return await next(input, init); - } catch (error) { - // Add context to the error - throw new Error(`Middleware error: ${error instanceof Error ? error.message : String(error)}`); - } - }; - - const originalError = new Error('Network failure'); - mockFetch.mockRejectedValue(originalError); - - const composedFetch = applyMiddlewares(errorMiddleware)(mockFetch); - - await expect(composedFetch('https://api.example.com/data')).rejects.toThrow('Middleware error: Network failure'); - }); -}); - -describe('Integration Tests', () => { - let mockProvider: jest.Mocked; - let mockFetch: jest.MockedFunction; - - beforeEach(() => { - jest.clearAllMocks(); - - mockProvider = { - get redirectUrl() { - return 'http://localhost/callback'; - }, - get clientMetadata() { - return { redirect_uris: ['http://localhost/callback'] }; - }, - tokens: jest.fn(), - saveTokens: jest.fn(), - clientInformation: jest.fn(), - redirectToAuthorization: jest.fn(), - saveCodeVerifier: jest.fn(), - codeVerifier: jest.fn(), - invalidateCredentials: jest.fn() - }; - - mockFetch = jest.fn(); - }); - - it('should work with SSE transport pattern', async () => { - // Simulate how SSE transport might use the middleware - mockProvider.tokens.mockResolvedValue({ - access_token: 'sse-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - const response = new Response('{"jsonrpc":"2.0","id":1,"result":{}}', { - status: 200, - headers: { 'Content-Type': 'application/json' } - }); - mockFetch.mockResolvedValue(response); - - // Use custom logger to avoid console output - const mockLogger = jest.fn(); - const enhancedFetch = applyMiddlewares( - withOAuth(mockProvider as OAuthClientProvider, 'https://mcp-server.example.com'), - withLogging({ logger: mockLogger, statusLevel: 400 }) // Only log errors - )(mockFetch); - - // Simulate SSE POST request - await enhancedFetch('https://mcp-server.example.com/endpoint', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - jsonrpc: '2.0', - method: 'tools/list', - id: 1 - }) - }); - - expect(mockFetch).toHaveBeenCalledWith( - 'https://mcp-server.example.com/endpoint', - expect.objectContaining({ - method: 'POST', - headers: expect.any(Headers), - body: expect.any(String) - }) - ); - - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('Authorization')).toBe('Bearer sse-token'); - expect(headers.get('Content-Type')).toBe('application/json'); - }); - - it('should work with StreamableHTTP transport pattern', async () => { - // Simulate how StreamableHTTP transport might use the middleware - mockProvider.tokens.mockResolvedValue({ - access_token: 'streamable-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - const response = new Response(null, { - status: 202, - headers: { 'mcp-session-id': 'session-123' } - }); - mockFetch.mockResolvedValue(response); - - // Use custom logger to avoid console output - const mockLogger = jest.fn(); - const enhancedFetch = applyMiddlewares( - withOAuth(mockProvider as OAuthClientProvider, 'https://streamable-server.example.com'), - withLogging({ - logger: mockLogger, - includeResponseHeaders: true, - statusLevel: 0 - }) - )(mockFetch); - - // Simulate StreamableHTTP initialization request - await enhancedFetch('https://streamable-server.example.com/mcp', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream' - }, - body: JSON.stringify({ - jsonrpc: '2.0', - method: 'initialize', - params: { protocolVersion: '2025-03-26', clientInfo: { name: 'test' } }, - id: 1 - }) - }); - - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('Authorization')).toBe('Bearer streamable-token'); - expect(headers.get('Accept')).toBe('application/json, text/event-stream'); - }); - - it('should handle auth retry in transport-like scenario', async () => { - mockProvider.tokens - .mockResolvedValueOnce({ - access_token: 'expired-token', - token_type: 'Bearer', - expires_in: 3600 - }) - .mockResolvedValueOnce({ - access_token: 'fresh-token', - token_type: 'Bearer', - expires_in: 3600 - }); - - const unauthorizedResponse = new Response('{"error":"invalid_token"}', { - status: 401, - headers: { 'www-authenticate': 'Bearer realm="mcp"' } - }); - const successResponse = new Response('{"jsonrpc":"2.0","id":1,"result":{}}', { - status: 200 - }); - - mockFetch.mockResolvedValueOnce(unauthorizedResponse).mockResolvedValueOnce(successResponse); - - mockExtractResourceMetadataUrl.mockReturnValue(new URL('https://auth.example.com/.well-known/oauth-protected-resource')); - mockAuth.mockResolvedValue('AUTHORIZED'); - - // Use custom logger to avoid console output - const mockLogger = jest.fn(); - const enhancedFetch = applyMiddlewares( - withOAuth(mockProvider as OAuthClientProvider, 'https://mcp-server.example.com'), - withLogging({ logger: mockLogger, statusLevel: 0 }) - )(mockFetch); - - const result = await enhancedFetch('https://mcp-server.example.com/endpoint', { - method: 'POST', - body: JSON.stringify({ jsonrpc: '2.0', method: 'test', id: 1 }) - }); - - expect(result).toBe(successResponse); - expect(mockFetch).toHaveBeenCalledTimes(2); - expect(mockAuth).toHaveBeenCalledWith(mockProvider, { - serverUrl: 'https://mcp-server.example.com', - resourceMetadataUrl: new URL('https://auth.example.com/.well-known/oauth-protected-resource'), - fetchFn: mockFetch - }); - }); -}); - -describe('createMiddleware', () => { - let mockFetch: jest.MockedFunction; - - beforeEach(() => { - jest.clearAllMocks(); - mockFetch = jest.fn(); - }); - - it('should create middleware with cleaner syntax', async () => { - const response = new Response('success', { status: 200 }); - mockFetch.mockResolvedValue(response); - - const customMiddleware = createMiddleware(async (next, input, init) => { - const headers = new Headers(init?.headers); - headers.set('X-Custom-Header', 'custom-value'); - return next(input, { ...init, headers }); - }); - - const enhancedFetch = customMiddleware(mockFetch); - await enhancedFetch('https://api.example.com/data'); - - expect(mockFetch).toHaveBeenCalledWith( - 'https://api.example.com/data', - expect.objectContaining({ - headers: expect.any(Headers) - }) - ); - - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('X-Custom-Header')).toBe('custom-value'); - }); - - it('should support conditional middleware logic', async () => { - const apiResponse = new Response('api response', { status: 200 }); - const publicResponse = new Response('public response', { status: 200 }); - mockFetch.mockResolvedValueOnce(apiResponse).mockResolvedValueOnce(publicResponse); - - const conditionalMiddleware = createMiddleware(async (next, input, init) => { - const url = typeof input === 'string' ? input : input.toString(); - - if (url.includes('/api/')) { - const headers = new Headers(init?.headers); - headers.set('X-API-Version', 'v2'); - return next(input, { ...init, headers }); - } - - return next(input, init); - }); - - const enhancedFetch = conditionalMiddleware(mockFetch); - - // Test API route - await enhancedFetch('https://example.com/api/users'); - let callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('X-API-Version')).toBe('v2'); - - // Test non-API route - await enhancedFetch('https://example.com/public/page'); - callArgs = mockFetch.mock.calls[1]; - const maybeHeaders = callArgs[1]?.headers as Headers | undefined; - expect(maybeHeaders?.get('X-API-Version')).toBeUndefined(); - }); - - it('should support short-circuit responses', async () => { - const customMiddleware = createMiddleware(async (next, input, init) => { - const url = typeof input === 'string' ? input : input.toString(); - - // Short-circuit for specific URL - if (url.includes('/cached')) { - return new Response('cached data', { status: 200 }); - } - - return next(input, init); - }); - - const enhancedFetch = customMiddleware(mockFetch); - - // Test cached route (should not call mockFetch) - const cachedResponse = await enhancedFetch('https://example.com/cached/data'); - expect(await cachedResponse.text()).toBe('cached data'); - expect(mockFetch).not.toHaveBeenCalled(); - - // Test normal route - mockFetch.mockResolvedValue(new Response('fresh data', { status: 200 })); - const normalResponse = await enhancedFetch('https://example.com/normal/data'); - expect(await normalResponse.text()).toBe('fresh data'); - expect(mockFetch).toHaveBeenCalledTimes(1); - }); - - it('should handle response transformation', async () => { - const originalResponse = new Response('{"data": "original"}', { - status: 200, - headers: { 'Content-Type': 'application/json' } - }); - mockFetch.mockResolvedValue(originalResponse); - - const transformMiddleware = createMiddleware(async (next, input, init) => { - const response = await next(input, init); - - if (response.headers.get('content-type')?.includes('application/json')) { - const data = await response.json(); - const transformed = { ...data, timestamp: 123456789 }; - - return new Response(JSON.stringify(transformed), { - status: response.status, - statusText: response.statusText, - headers: response.headers - }); - } - - return response; - }); - - const enhancedFetch = transformMiddleware(mockFetch); - const response = await enhancedFetch('https://api.example.com/data'); - const result = await response.json(); - - expect(result).toEqual({ - data: 'original', - timestamp: 123456789 - }); - }); - - it('should support error handling and recovery', async () => { - let attemptCount = 0; - mockFetch.mockImplementation(async () => { - attemptCount++; - if (attemptCount === 1) { - throw new Error('Network error'); - } - return new Response('success', { status: 200 }); - }); - - const retryMiddleware = createMiddleware(async (next, input, init) => { - try { - return await next(input, init); - } catch (error) { - // Retry once on network error - console.log('Retrying request after error:', error); - return await next(input, init); - } - }); - - const enhancedFetch = retryMiddleware(mockFetch); - const response = await enhancedFetch('https://api.example.com/data'); - - expect(await response.text()).toBe('success'); - expect(mockFetch).toHaveBeenCalledTimes(2); - }); - - it('should compose well with other middleware', async () => { - const response = new Response('success', { status: 200 }); - mockFetch.mockResolvedValue(response); - - // Create custom middleware using createMiddleware - const customAuth = createMiddleware(async (next, input, init) => { - const headers = new Headers(init?.headers); - headers.set('Authorization', 'Custom token'); - return next(input, { ...init, headers }); - }); - - const customLogging = createMiddleware(async (next, input, init) => { - const url = typeof input === 'string' ? input : input.toString(); - console.log(`Request to: ${url}`); - const response = await next(input, init); - console.log(`Response status: ${response.status}`); - return response; - }); - - // Compose with existing middleware - const enhancedFetch = applyMiddlewares(customAuth, customLogging, withLogging({ statusLevel: 400 }))(mockFetch); - - await enhancedFetch('https://api.example.com/data'); - - const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs[1]?.headers as Headers; - expect(headers.get('Authorization')).toBe('Custom token'); - }); - - it('should have access to both input types (string and URL)', async () => { - const response = new Response('success', { status: 200 }); - mockFetch.mockResolvedValue(response); - - let capturedInputType: string | undefined; - const inspectMiddleware = createMiddleware(async (next, input, init) => { - capturedInputType = typeof input === 'string' ? 'string' : 'URL'; - return next(input, init); - }); - - const enhancedFetch = inspectMiddleware(mockFetch); - - // Test with string input - await enhancedFetch('https://api.example.com/data'); - expect(capturedInputType).toBe('string'); - - // Test with URL input - await enhancedFetch(new URL('https://api.example.com/data')); - expect(capturedInputType).toBe('URL'); - }); -}); diff --git a/typescript-sdk/src/client/middleware.ts b/typescript-sdk/src/client/middleware.ts deleted file mode 100644 index a7cbc6c..0000000 --- a/typescript-sdk/src/client/middleware.ts +++ /dev/null @@ -1,319 +0,0 @@ -import { auth, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from './auth.js'; -import { FetchLike } from '../shared/transport.js'; - -/** - * Middleware function that wraps and enhances fetch functionality. - * Takes a fetch handler and returns an enhanced fetch handler. - */ -export type Middleware = (next: FetchLike) => FetchLike; - -/** - * Creates a fetch wrapper that handles OAuth authentication automatically. - * - * This wrapper will: - * - Add Authorization headers with access tokens - * - Handle 401 responses by attempting re-authentication - * - Retry the original request after successful auth - * - Handle OAuth errors appropriately (InvalidClientError, etc.) - * - * The baseUrl parameter is optional and defaults to using the domain from the request URL. - * However, you should explicitly provide baseUrl when: - * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) - * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) - * - The OAuth server is on a different domain than your API requests - * - You want to ensure consistent OAuth behavior regardless of request URLs - * - * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. - * - * Note: This wrapper is designed for general-purpose fetch operations. - * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling - * and should not need this wrapper. - * - * @param provider - OAuth client provider for authentication - * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) - * @returns A fetch middleware function - */ -export const withOAuth = - (provider: OAuthClientProvider, baseUrl?: string | URL): Middleware => - next => { - return async (input, init) => { - const makeRequest = async (): Promise => { - const headers = new Headers(init?.headers); - - // Add authorization header if tokens are available - const tokens = await provider.tokens(); - if (tokens) { - headers.set('Authorization', `Bearer ${tokens.access_token}`); - } - - return await next(input, { ...init, headers }); - }; - - let response = await makeRequest(); - - // Handle 401 responses by attempting re-authentication - if (response.status === 401) { - try { - const resourceMetadataUrl = extractResourceMetadataUrl(response); - - // Use provided baseUrl or extract from request URL - const serverUrl = baseUrl || (typeof input === 'string' ? new URL(input).origin : input.origin); - - const result = await auth(provider, { - serverUrl, - resourceMetadataUrl, - fetchFn: next - }); - - if (result === 'REDIRECT') { - throw new UnauthorizedError('Authentication requires user authorization - redirect initiated'); - } - - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(`Authentication failed with result: ${result}`); - } - - // Retry the request with fresh tokens - response = await makeRequest(); - } catch (error) { - if (error instanceof UnauthorizedError) { - throw error; - } - throw new UnauthorizedError(`Failed to re-authenticate: ${error instanceof Error ? error.message : String(error)}`); - } - } - - // If we still have a 401 after re-auth attempt, throw an error - if (response.status === 401) { - const url = typeof input === 'string' ? input : input.toString(); - throw new UnauthorizedError(`Authentication failed for ${url}`); - } - - return response; - }; - }; - -/** - * Logger function type for HTTP requests - */ -export type RequestLogger = (input: { - method: string; - url: string | URL; - status: number; - statusText: string; - duration: number; - requestHeaders?: Headers; - responseHeaders?: Headers; - error?: Error; -}) => void; - -/** - * Configuration options for the logging middleware - */ -export type LoggingOptions = { - /** - * Custom logger function, defaults to console logging - */ - logger?: RequestLogger; - - /** - * Whether to include request headers in logs - * @default false - */ - includeRequestHeaders?: boolean; - - /** - * Whether to include response headers in logs - * @default false - */ - includeResponseHeaders?: boolean; - - /** - * Status level filter - only log requests with status >= this value - * Set to 0 to log all requests, 400 to log only errors - * @default 0 - */ - statusLevel?: number; -}; - -/** - * Creates a fetch middleware that logs HTTP requests and responses. - * - * When called without arguments `withLogging()`, it uses the default logger that: - * - Logs successful requests (2xx) to `console.log` - * - Logs error responses (4xx/5xx) and network errors to `console.error` - * - Logs all requests regardless of status (statusLevel: 0) - * - Does not include request or response headers in logs - * - Measures and displays request duration in milliseconds - * - * Important: the default logger uses both `console.log` and `console.error` so it should not be used with - * `stdio` transports and applications. - * - * @param options - Logging configuration options - * @returns A fetch middleware function - */ -export const withLogging = (options: LoggingOptions = {}): Middleware => { - const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options; - - const defaultLogger: RequestLogger = input => { - const { method, url, status, statusText, duration, requestHeaders, responseHeaders, error } = input; - - let message = error - ? `HTTP ${method} ${url} failed: ${error.message} (${duration}ms)` - : `HTTP ${method} ${url} ${status} ${statusText} (${duration}ms)`; - - // Add headers to message if requested - if (includeRequestHeaders && requestHeaders) { - const reqHeaders = Array.from(requestHeaders.entries()) - .map(([key, value]) => `${key}: ${value}`) - .join(', '); - message += `\n Request Headers: {${reqHeaders}}`; - } - - if (includeResponseHeaders && responseHeaders) { - const resHeaders = Array.from(responseHeaders.entries()) - .map(([key, value]) => `${key}: ${value}`) - .join(', '); - message += `\n Response Headers: {${resHeaders}}`; - } - - if (error || status >= 400) { - // eslint-disable-next-line no-console - console.error(message); - } else { - // eslint-disable-next-line no-console - console.log(message); - } - }; - - const logFn = logger || defaultLogger; - - return next => async (input, init) => { - const startTime = performance.now(); - const method = init?.method || 'GET'; - const url = typeof input === 'string' ? input : input.toString(); - const requestHeaders = includeRequestHeaders ? new Headers(init?.headers) : undefined; - - try { - const response = await next(input, init); - const duration = performance.now() - startTime; - - // Only log if status meets the log level threshold - if (response.status >= statusLevel) { - logFn({ - method, - url, - status: response.status, - statusText: response.statusText, - duration, - requestHeaders, - responseHeaders: includeResponseHeaders ? response.headers : undefined - }); - } - - return response; - } catch (error) { - const duration = performance.now() - startTime; - - // Always log errors regardless of log level - logFn({ - method, - url, - status: 0, - statusText: 'Network Error', - duration, - requestHeaders, - error: error as Error - }); - - throw error; - } - }; -}; - -/** - * Composes multiple fetch middleware functions into a single middleware pipeline. - * Middleware are applied in the order they appear, creating a chain of handlers. - * - * @example - * ```typescript - * // Create a middleware pipeline that handles both OAuth and logging - * const enhancedFetch = applyMiddlewares( - * withOAuth(oauthProvider, 'https://api.example.com'), - * withLogging({ statusLevel: 400 }) - * )(fetch); - * - * // Use the enhanced fetch - it will handle auth and log errors - * const response = await enhancedFetch('https://api.example.com/data'); - * ``` - * - * @param middleware - Array of fetch middleware to compose into a pipeline - * @returns A single composed middleware function - */ -export const applyMiddlewares = (...middleware: Middleware[]): Middleware => { - return next => { - return middleware.reduce((handler, mw) => mw(handler), next); - }; -}; - -/** - * Helper function to create custom fetch middleware with cleaner syntax. - * Provides the next handler and request details as separate parameters for easier access. - * - * @example - * ```typescript - * // Create custom authentication middleware - * const customAuthMiddleware = createMiddleware(async (next, input, init) => { - * const headers = new Headers(init?.headers); - * headers.set('X-Custom-Auth', 'my-token'); - * - * const response = await next(input, { ...init, headers }); - * - * if (response.status === 401) { - * console.log('Authentication failed'); - * } - * - * return response; - * }); - * - * // Create conditional middleware - * const conditionalMiddleware = createMiddleware(async (next, input, init) => { - * const url = typeof input === 'string' ? input : input.toString(); - * - * // Only add headers for API routes - * if (url.includes('/api/')) { - * const headers = new Headers(init?.headers); - * headers.set('X-API-Version', 'v2'); - * return next(input, { ...init, headers }); - * } - * - * // Pass through for non-API routes - * return next(input, init); - * }); - * - * // Create caching middleware - * const cacheMiddleware = createMiddleware(async (next, input, init) => { - * const cacheKey = typeof input === 'string' ? input : input.toString(); - * - * // Check cache first - * const cached = await getFromCache(cacheKey); - * if (cached) { - * return new Response(cached, { status: 200 }); - * } - * - * // Make request and cache result - * const response = await next(input, init); - * if (response.ok) { - * await saveToCache(cacheKey, await response.clone().text()); - * } - * - * return response; - * }); - * ``` - * - * @param handler - Function that receives the next handler and request parameters - * @returns A fetch middleware function - */ -export const createMiddleware = (handler: (next: FetchLike, input: string | URL, init?: RequestInit) => Promise): Middleware => { - return next => (input, init) => handler(next, input as string | URL, init); -}; diff --git a/typescript-sdk/src/client/sse.test.ts b/typescript-sdk/src/client/sse.test.ts deleted file mode 100644 index 9e4b73e..0000000 --- a/typescript-sdk/src/client/sse.test.ts +++ /dev/null @@ -1,1484 +0,0 @@ -import { createServer, ServerResponse, type IncomingMessage, type Server } from 'http'; -import { AddressInfo } from 'net'; -import { JSONRPCMessage } from '../types.js'; -import { SSEClientTransport } from './sse.js'; -import { OAuthClientProvider, UnauthorizedError } from './auth.js'; -import { OAuthTokens } from '../shared/auth.js'; -import { InvalidClientError, InvalidGrantError, UnauthorizedClientError } from '../server/auth/errors.js'; - -describe('SSEClientTransport', () => { - let resourceServer: Server; - let authServer: Server; - let transport: SSEClientTransport; - let resourceBaseUrl: URL; - let authBaseUrl: URL; - let lastServerRequest: IncomingMessage; - let sendServerMessage: ((message: string) => void) | null = null; - - beforeEach(done => { - // Reset state - lastServerRequest = null as unknown as IncomingMessage; - sendServerMessage = null; - - authServer = createServer((req, res) => { - if (req.url === '/.well-known/oauth-authorization-server') { - res.writeHead(200, { - 'Content-Type': 'application/json' - }); - res.end( - JSON.stringify({ - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - registration_endpoint: 'https://auth.example.com/register', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - ); - return; - } - res.writeHead(401).end(); - }); - - // Create a test server that will receive the EventSource connection - resourceServer = createServer((req, res) => { - lastServerRequest = req; - - // Send SSE headers - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }); - - // Send the endpoint event - res.write('event: endpoint\n'); - res.write(`data: ${resourceBaseUrl.href}\n\n`); - - // Store reference to send function for tests - sendServerMessage = (message: string) => { - res.write(`data: ${message}\n\n`); - }; - - // Handle request body for POST endpoints - if (req.method === 'POST') { - let body = ''; - req.on('data', chunk => { - body += chunk; - }); - req.on('end', () => { - (req as IncomingMessage & { body: string }).body = body; - res.end(); - }); - } - }); - - // Start server on random port - resourceServer.listen(0, '127.0.0.1', () => { - const addr = resourceServer.address() as AddressInfo; - resourceBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - done(); - }); - - jest.spyOn(console, 'error').mockImplementation(() => {}); - }); - - afterEach(async () => { - await transport.close(); - await resourceServer.close(); - await authServer.close(); - - jest.clearAllMocks(); - }); - - describe('connection handling', () => { - it('establishes SSE connection and receives endpoint', async () => { - transport = new SSEClientTransport(resourceBaseUrl); - await transport.start(); - - expect(lastServerRequest.headers.accept).toBe('text/event-stream'); - expect(lastServerRequest.method).toBe('GET'); - }); - - it('rejects if server returns non-200 status', async () => { - // Create a server that returns 403 - await resourceServer.close(); - - resourceServer = createServer((req, res) => { - res.writeHead(403); - res.end(); - }); - - await new Promise(resolve => { - resourceServer.listen(0, '127.0.0.1', () => { - const addr = resourceServer.address() as AddressInfo; - resourceBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - transport = new SSEClientTransport(resourceBaseUrl); - await expect(transport.start()).rejects.toThrow(); - }); - - it('closes EventSource connection on close()', async () => { - transport = new SSEClientTransport(resourceBaseUrl); - await transport.start(); - - const closePromise = new Promise(resolve => { - lastServerRequest.on('close', resolve); - }); - - await transport.close(); - await closePromise; - }); - }); - - describe('message handling', () => { - it('receives and parses JSON-RPC messages', async () => { - const receivedMessages: JSONRPCMessage[] = []; - transport = new SSEClientTransport(resourceBaseUrl); - transport.onmessage = msg => receivedMessages.push(msg); - - await transport.start(); - - const testMessage: JSONRPCMessage = { - jsonrpc: '2.0', - id: 'test-1', - method: 'test', - params: { foo: 'bar' } - }; - - sendServerMessage!(JSON.stringify(testMessage)); - - // Wait for message processing - await new Promise(resolve => setTimeout(resolve, 50)); - - expect(receivedMessages).toHaveLength(1); - expect(receivedMessages[0]).toEqual(testMessage); - }); - - it('handles malformed JSON messages', async () => { - const errors: Error[] = []; - transport = new SSEClientTransport(resourceBaseUrl); - transport.onerror = err => errors.push(err); - - await transport.start(); - - sendServerMessage!('invalid json'); - - // Wait for message processing - await new Promise(resolve => setTimeout(resolve, 50)); - - expect(errors).toHaveLength(1); - expect(errors[0].message).toMatch(/JSON/); - }); - - it('handles messages via POST requests', async () => { - transport = new SSEClientTransport(resourceBaseUrl); - await transport.start(); - - const testMessage: JSONRPCMessage = { - jsonrpc: '2.0', - id: 'test-1', - method: 'test', - params: { foo: 'bar' } - }; - - await transport.send(testMessage); - - // Wait for request processing - await new Promise(resolve => setTimeout(resolve, 50)); - - expect(lastServerRequest.method).toBe('POST'); - expect(lastServerRequest.headers['content-type']).toBe('application/json'); - expect(JSON.parse((lastServerRequest as IncomingMessage & { body: string }).body)).toEqual(testMessage); - }); - - it('handles POST request failures', async () => { - // Create a server that returns 500 for POST - await resourceServer.close(); - - resourceServer = createServer((req, res) => { - if (req.method === 'GET') { - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }); - res.write('event: endpoint\n'); - res.write(`data: ${resourceBaseUrl.href}\n\n`); - } else { - res.writeHead(500); - res.end('Internal error'); - } - }); - - await new Promise(resolve => { - resourceServer.listen(0, '127.0.0.1', () => { - const addr = resourceServer.address() as AddressInfo; - resourceBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - transport = new SSEClientTransport(resourceBaseUrl); - await transport.start(); - - const testMessage: JSONRPCMessage = { - jsonrpc: '2.0', - id: 'test-1', - method: 'test', - params: {} - }; - - await expect(transport.send(testMessage)).rejects.toThrow(/500/); - }); - }); - - describe('header handling', () => { - it('uses custom fetch implementation from EventSourceInit to add auth headers', async () => { - const authToken = 'Bearer test-token'; - - // Create a fetch wrapper that adds auth header - const fetchWithAuth = (url: string | URL, init?: RequestInit) => { - const headers = new Headers(init?.headers); - headers.set('Authorization', authToken); - return fetch(url.toString(), { ...init, headers }); - }; - - transport = new SSEClientTransport(resourceBaseUrl, { - eventSourceInit: { - fetch: fetchWithAuth - } - }); - - await transport.start(); - - // Verify the auth header was received by the server - expect(lastServerRequest.headers.authorization).toBe(authToken); - }); - - it('uses custom fetch implementation from options', async () => { - const authToken = 'Bearer custom-token'; - - const fetchWithAuth = jest.fn((url: string | URL, init?: RequestInit) => { - const headers = new Headers(init?.headers); - headers.set('Authorization', authToken); - return fetch(url.toString(), { ...init, headers }); - }); - - transport = new SSEClientTransport(resourceBaseUrl, { - fetch: fetchWithAuth - }); - - await transport.start(); - - expect(lastServerRequest.headers.authorization).toBe(authToken); - - // Send a message to verify fetchWithAuth used for POST as well - const message: JSONRPCMessage = { - jsonrpc: '2.0', - id: '1', - method: 'test', - params: {} - }; - - await transport.send(message); - - expect(fetchWithAuth).toHaveBeenCalledTimes(2); - expect(lastServerRequest.method).toBe('POST'); - expect(lastServerRequest.headers.authorization).toBe(authToken); - }); - - it('passes custom headers to fetch requests', async () => { - const customHeaders = { - Authorization: 'Bearer test-token', - 'X-Custom-Header': 'custom-value' - }; - - transport = new SSEClientTransport(resourceBaseUrl, { - requestInit: { - headers: customHeaders - } - }); - - await transport.start(); - - // Store original fetch - const originalFetch = global.fetch; - - try { - // Mock fetch for the message sending test - global.fetch = jest.fn().mockResolvedValue({ - ok: true - }); - - const message: JSONRPCMessage = { - jsonrpc: '2.0', - id: '1', - method: 'test', - params: {} - }; - - await transport.send(message); - - // Verify fetch was called with correct headers - expect(global.fetch).toHaveBeenCalledWith( - expect.any(URL), - expect.objectContaining({ - headers: expect.any(Headers) - }) - ); - - const calledHeaders = (global.fetch as jest.Mock).mock.calls[0][1].headers; - expect(calledHeaders.get('Authorization')).toBe(customHeaders.Authorization); - expect(calledHeaders.get('X-Custom-Header')).toBe(customHeaders['X-Custom-Header']); - expect(calledHeaders.get('content-type')).toBe('application/json'); - } finally { - // Restore original fetch - global.fetch = originalFetch; - } - }); - }); - - describe('auth handling', () => { - const authServerMetadataUrls = ['/.well-known/oauth-authorization-server', '/.well-known/openid-configuration']; - - let mockAuthProvider: jest.Mocked; - - beforeEach(() => { - mockAuthProvider = { - get redirectUrl() { - return 'http://localhost/callback'; - }, - get clientMetadata() { - return { redirect_uris: ['http://localhost/callback'] }; - }, - clientInformation: jest.fn(() => ({ client_id: 'test-client-id', client_secret: 'test-client-secret' })), - tokens: jest.fn(), - saveTokens: jest.fn(), - redirectToAuthorization: jest.fn(), - saveCodeVerifier: jest.fn(), - codeVerifier: jest.fn(), - invalidateCredentials: jest.fn() - }; - }); - - it('attaches auth header from provider on SSE connection', async () => { - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer' - }); - - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider - }); - - await transport.start(); - - expect(lastServerRequest.headers.authorization).toBe('Bearer test-token'); - expect(mockAuthProvider.tokens).toHaveBeenCalled(); - }); - - it('attaches custom header from provider on initial SSE connection', async () => { - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer' - }); - const customHeaders = { - 'X-Custom-Header': 'custom-value' - }; - - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider, - requestInit: { - headers: customHeaders - } - }); - - await transport.start(); - - expect(lastServerRequest.headers.authorization).toBe('Bearer test-token'); - expect(lastServerRequest.headers['x-custom-header']).toBe('custom-value'); - expect(mockAuthProvider.tokens).toHaveBeenCalled(); - }); - - it('attaches auth header from provider on POST requests', async () => { - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer' - }); - - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider - }); - - await transport.start(); - - const message: JSONRPCMessage = { - jsonrpc: '2.0', - id: '1', - method: 'test', - params: {} - }; - - await transport.send(message); - - expect(lastServerRequest.headers.authorization).toBe('Bearer test-token'); - expect(mockAuthProvider.tokens).toHaveBeenCalled(); - }); - - it('attempts auth flow on 401 during SSE connection', async () => { - // Create server that returns 401s - resourceServer.close(); - authServer.close(); - - // Start auth server on random port - await new Promise(resolve => { - authServer.listen(0, '127.0.0.1', () => { - const addr = authServer.address() as AddressInfo; - authBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - resourceServer = createServer((req, res) => { - lastServerRequest = req; - - if (req.url === '/.well-known/oauth-protected-resource') { - res.writeHead(200, { - 'Content-Type': 'application/json' - }).end( - JSON.stringify({ - resource: resourceBaseUrl.href, - authorization_servers: [`${authBaseUrl}`] - }) - ); - return; - } - - if (req.url !== '/') { - res.writeHead(404).end(); - } else { - res.writeHead(401).end(); - } - }); - - await new Promise(resolve => { - resourceServer.listen(0, '127.0.0.1', () => { - const addr = resourceServer.address() as AddressInfo; - resourceBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider - }); - - await expect(() => transport.start()).rejects.toThrow(UnauthorizedError); - expect(mockAuthProvider.redirectToAuthorization.mock.calls).toHaveLength(1); - }); - - it('attempts auth flow on 401 during POST request', async () => { - // Create server that accepts SSE but returns 401 on POST - resourceServer.close(); - authServer.close(); - - await new Promise(resolve => { - authServer.listen(0, '127.0.0.1', () => { - const addr = authServer.address() as AddressInfo; - authBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - resourceServer = createServer((req, res) => { - lastServerRequest = req; - - switch (req.method) { - case 'GET': - if (req.url === '/.well-known/oauth-protected-resource') { - res.writeHead(200, { - 'Content-Type': 'application/json' - }).end( - JSON.stringify({ - resource: resourceBaseUrl.href, - authorization_servers: [`${authBaseUrl}`] - }) - ); - return; - } - - if (req.url !== '/') { - res.writeHead(404).end(); - return; - } - - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }); - res.write('event: endpoint\n'); - res.write(`data: ${resourceBaseUrl.href}\n\n`); - break; - - case 'POST': - res.writeHead(401); - res.end(); - break; - } - }); - - await new Promise(resolve => { - resourceServer.listen(0, '127.0.0.1', () => { - const addr = resourceServer.address() as AddressInfo; - resourceBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider - }); - - await transport.start(); - - const message: JSONRPCMessage = { - jsonrpc: '2.0', - id: '1', - method: 'test', - params: {} - }; - - await expect(() => transport.send(message)).rejects.toThrow(UnauthorizedError); - expect(mockAuthProvider.redirectToAuthorization.mock.calls).toHaveLength(1); - }); - - it('respects custom headers when using auth provider', async () => { - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer' - }); - - const customHeaders = { - 'X-Custom-Header': 'custom-value' - }; - - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider, - requestInit: { - headers: customHeaders - } - }); - - await transport.start(); - - const message: JSONRPCMessage = { - jsonrpc: '2.0', - id: '1', - method: 'test', - params: {} - }; - - await transport.send(message); - - expect(lastServerRequest.headers.authorization).toBe('Bearer test-token'); - expect(lastServerRequest.headers['x-custom-header']).toBe('custom-value'); - }); - - it('refreshes expired token during SSE connection', async () => { - // Mock tokens() to return expired token until saveTokens is called - let currentTokens: OAuthTokens = { - access_token: 'expired-token', - token_type: 'Bearer', - refresh_token: 'refresh-token' - }; - mockAuthProvider.tokens.mockImplementation(() => currentTokens); - mockAuthProvider.saveTokens.mockImplementation(tokens => { - currentTokens = tokens; - }); - - // Create server that returns 401 for expired token, then accepts new token - resourceServer.close(); - authServer.close(); - - authServer = createServer((req, res) => { - if (req.url && authServerMetadataUrls.includes(req.url)) { - res.writeHead(404).end(); - return; - } - - if (req.url === '/token' && req.method === 'POST') { - // Handle token refresh request - let body = ''; - req.on('data', chunk => { - body += chunk; - }); - req.on('end', () => { - const params = new URLSearchParams(body); - if ( - params.get('grant_type') === 'refresh_token' && - params.get('refresh_token') === 'refresh-token' && - params.get('client_id') === 'test-client-id' && - params.get('client_secret') === 'test-client-secret' - ) { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end( - JSON.stringify({ - access_token: 'new-token', - token_type: 'Bearer', - refresh_token: 'new-refresh-token' - }) - ); - } else { - res.writeHead(400).end(); - } - }); - return; - } - - res.writeHead(401).end(); - }); - - // Start auth server on random port - await new Promise(resolve => { - authServer.listen(0, '127.0.0.1', () => { - const addr = authServer.address() as AddressInfo; - authBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - let connectionAttempts = 0; - resourceServer = createServer((req, res) => { - lastServerRequest = req; - - if (req.url === '/.well-known/oauth-protected-resource') { - res.writeHead(200, { - 'Content-Type': 'application/json' - }).end( - JSON.stringify({ - resource: resourceBaseUrl.href, - authorization_servers: [`${authBaseUrl}`] - }) - ); - return; - } - - if (req.url !== '/') { - res.writeHead(404).end(); - return; - } - - const auth = req.headers.authorization; - if (auth === 'Bearer expired-token') { - res.writeHead(401).end(); - return; - } - - if (auth === 'Bearer new-token') { - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }); - res.write('event: endpoint\n'); - res.write(`data: ${resourceBaseUrl.href}\n\n`); - connectionAttempts++; - return; - } - - res.writeHead(401).end(); - }); - - await new Promise(resolve => { - resourceServer.listen(0, '127.0.0.1', () => { - const addr = resourceServer.address() as AddressInfo; - resourceBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider - }); - - await transport.start(); - - expect(mockAuthProvider.saveTokens).toHaveBeenCalledWith({ - access_token: 'new-token', - token_type: 'Bearer', - refresh_token: 'new-refresh-token' - }); - expect(connectionAttempts).toBe(1); - expect(lastServerRequest.headers.authorization).toBe('Bearer new-token'); - }); - - it('refreshes expired token during POST request', async () => { - // Mock tokens() to return expired token until saveTokens is called - let currentTokens: OAuthTokens = { - access_token: 'expired-token', - token_type: 'Bearer', - refresh_token: 'refresh-token' - }; - mockAuthProvider.tokens.mockImplementation(() => currentTokens); - mockAuthProvider.saveTokens.mockImplementation(tokens => { - currentTokens = tokens; - }); - - // Create server that returns 401 for expired token, then accepts new token - resourceServer.close(); - authServer.close(); - - authServer = createServer((req, res) => { - if (req.url && authServerMetadataUrls.includes(req.url)) { - res.writeHead(404).end(); - return; - } - - if (req.url === '/token' && req.method === 'POST') { - // Handle token refresh request - let body = ''; - req.on('data', chunk => { - body += chunk; - }); - req.on('end', () => { - const params = new URLSearchParams(body); - if ( - params.get('grant_type') === 'refresh_token' && - params.get('refresh_token') === 'refresh-token' && - params.get('client_id') === 'test-client-id' && - params.get('client_secret') === 'test-client-secret' - ) { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end( - JSON.stringify({ - access_token: 'new-token', - token_type: 'Bearer', - refresh_token: 'new-refresh-token' - }) - ); - } else { - res.writeHead(400).end(); - } - }); - return; - } - - res.writeHead(401).end(); - }); - - // Start auth server on random port - await new Promise(resolve => { - authServer.listen(0, '127.0.0.1', () => { - const addr = authServer.address() as AddressInfo; - authBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - let postAttempts = 0; - resourceServer = createServer((req, res) => { - lastServerRequest = req; - - if (req.url === '/.well-known/oauth-protected-resource') { - res.writeHead(200, { - 'Content-Type': 'application/json' - }).end( - JSON.stringify({ - resource: resourceBaseUrl.href, - authorization_servers: [`${authBaseUrl}`] - }) - ); - return; - } - - switch (req.method) { - case 'GET': - if (req.url !== '/') { - res.writeHead(404).end(); - return; - } - - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }); - res.write('event: endpoint\n'); - res.write(`data: ${resourceBaseUrl.href}\n\n`); - break; - - case 'POST': { - if (req.url !== '/') { - res.writeHead(404).end(); - return; - } - - const auth = req.headers.authorization; - if (auth === 'Bearer expired-token') { - res.writeHead(401).end(); - return; - } - - if (auth === 'Bearer new-token') { - res.writeHead(200).end(); - postAttempts++; - return; - } - - res.writeHead(401).end(); - break; - } - } - }); - - await new Promise(resolve => { - resourceServer.listen(0, '127.0.0.1', () => { - const addr = resourceServer.address() as AddressInfo; - resourceBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider - }); - - await transport.start(); - - const message: JSONRPCMessage = { - jsonrpc: '2.0', - id: '1', - method: 'test', - params: {} - }; - - await transport.send(message); - - expect(mockAuthProvider.saveTokens).toHaveBeenCalledWith({ - access_token: 'new-token', - token_type: 'Bearer', - refresh_token: 'new-refresh-token' - }); - expect(postAttempts).toBe(1); - expect(lastServerRequest.headers.authorization).toBe('Bearer new-token'); - }); - - it('redirects to authorization if refresh token flow fails', async () => { - // Mock tokens() to return expired token until saveTokens is called - let currentTokens: OAuthTokens = { - access_token: 'expired-token', - token_type: 'Bearer', - refresh_token: 'refresh-token' - }; - mockAuthProvider.tokens.mockImplementation(() => currentTokens); - mockAuthProvider.saveTokens.mockImplementation(tokens => { - currentTokens = tokens; - }); - - // Create server that returns 401 for all tokens - resourceServer.close(); - authServer.close(); - - authServer = createServer((req, res) => { - if (req.url && authServerMetadataUrls.includes(req.url)) { - res.writeHead(404).end(); - return; - } - - if (req.url === '/token' && req.method === 'POST') { - // Handle token refresh request - always fail - res.writeHead(400).end(); - return; - } - - res.writeHead(401).end(); - }); - - // Start auth server on random port - await new Promise(resolve => { - authServer.listen(0, '127.0.0.1', () => { - const addr = authServer.address() as AddressInfo; - authBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - resourceServer = createServer((req, res) => { - lastServerRequest = req; - - if (req.url === '/.well-known/oauth-protected-resource') { - res.writeHead(200, { - 'Content-Type': 'application/json' - }).end( - JSON.stringify({ - resource: resourceBaseUrl.href, - authorization_servers: [`${authBaseUrl}`] - }) - ); - return; - } - - if (req.url !== '/') { - res.writeHead(404).end(); - return; - } - res.writeHead(401).end(); - }); - - await new Promise(resolve => { - resourceServer.listen(0, '127.0.0.1', () => { - const addr = resourceServer.address() as AddressInfo; - resourceBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider - }); - - await expect(() => transport.start()).rejects.toThrow(UnauthorizedError); - expect(mockAuthProvider.redirectToAuthorization).toHaveBeenCalled(); - }); - - it('invalidates all credentials on InvalidClientError during token refresh', async () => { - // Mock tokens() to return token with refresh token - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'expired-token', - token_type: 'Bearer', - refresh_token: 'refresh-token' - }); - - let baseUrl = resourceBaseUrl; - - // Create server that returns InvalidClientError on token refresh - const server = createServer((req, res) => { - lastServerRequest = req; - - // Handle OAuth metadata discovery - if (req.url === '/.well-known/oauth-authorization-server' && req.method === 'GET') { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end( - JSON.stringify({ - issuer: baseUrl.href, - authorization_endpoint: `${baseUrl.href}authorize`, - token_endpoint: `${baseUrl.href}token`, - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - ); - return; - } - - if (req.url === '/token' && req.method === 'POST') { - // Handle token refresh request - return InvalidClientError - const error = new InvalidClientError('Client authentication failed'); - res.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify(error.toResponseObject())); - return; - } - - if (req.url !== '/') { - res.writeHead(404).end(); - return; - } - res.writeHead(401).end(); - }); - - await new Promise(resolve => { - server.listen(0, '127.0.0.1', () => { - const addr = server.address() as AddressInfo; - baseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - transport = new SSEClientTransport(baseUrl, { - authProvider: mockAuthProvider - }); - - await expect(() => transport.start()).rejects.toThrow(InvalidClientError); - expect(mockAuthProvider.invalidateCredentials).toHaveBeenCalledWith('all'); - }); - - it('invalidates all credentials on UnauthorizedClientError during token refresh', async () => { - // Mock tokens() to return token with refresh token - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'expired-token', - token_type: 'Bearer', - refresh_token: 'refresh-token' - }); - - let baseUrl = resourceBaseUrl; - - const server = createServer((req, res) => { - lastServerRequest = req; - - // Handle OAuth metadata discovery - if (req.url === '/.well-known/oauth-authorization-server' && req.method === 'GET') { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end( - JSON.stringify({ - issuer: baseUrl.href, - authorization_endpoint: `${baseUrl.href}authorize`, - token_endpoint: `${baseUrl.href}token`, - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - ); - return; - } - - if (req.url === '/token' && req.method === 'POST') { - // Handle token refresh request - return UnauthorizedClientError - const error = new UnauthorizedClientError('Client not authorized'); - res.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify(error.toResponseObject())); - return; - } - - if (req.url !== '/') { - res.writeHead(404).end(); - return; - } - res.writeHead(401).end(); - }); - - await new Promise(resolve => { - server.listen(0, '127.0.0.1', () => { - const addr = server.address() as AddressInfo; - baseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - transport = new SSEClientTransport(baseUrl, { - authProvider: mockAuthProvider - }); - - await expect(() => transport.start()).rejects.toThrow(UnauthorizedClientError); - expect(mockAuthProvider.invalidateCredentials).toHaveBeenCalledWith('all'); - }); - - it('invalidates tokens on InvalidGrantError during token refresh', async () => { - // Mock tokens() to return token with refresh token - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'expired-token', - token_type: 'Bearer', - refresh_token: 'refresh-token' - }); - let baseUrl = resourceBaseUrl; - - const server = createServer((req, res) => { - lastServerRequest = req; - - // Handle OAuth metadata discovery - if (req.url === '/.well-known/oauth-authorization-server' && req.method === 'GET') { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end( - JSON.stringify({ - issuer: baseUrl.href, - authorization_endpoint: `${baseUrl.href}authorize`, - token_endpoint: `${baseUrl.href}token`, - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - ); - return; - } - - if (req.url === '/token' && req.method === 'POST') { - // Handle token refresh request - return InvalidGrantError - const error = new InvalidGrantError('Invalid refresh token'); - res.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify(error.toResponseObject())); - return; - } - - if (req.url !== '/') { - res.writeHead(404).end(); - return; - } - res.writeHead(401).end(); - }); - - await new Promise(resolve => { - server.listen(0, '127.0.0.1', () => { - const addr = server.address() as AddressInfo; - baseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - - transport = new SSEClientTransport(baseUrl, { - authProvider: mockAuthProvider - }); - - await expect(() => transport.start()).rejects.toThrow(InvalidGrantError); - expect(mockAuthProvider.invalidateCredentials).toHaveBeenCalledWith('tokens'); - }); - }); - - describe('custom fetch in auth code paths', () => { - let customFetch: jest.MockedFunction; - let globalFetchSpy: jest.SpyInstance; - let mockAuthProvider: jest.Mocked; - let resourceServerHandler: jest.Mock< - void, - [ - IncomingMessage, - ServerResponse & { - req: IncomingMessage; - } - ], - void - >; - - /** - * Helper function to create a mock auth provider with configurable behavior - */ - const createMockAuthProvider = ( - config: { - hasTokens?: boolean; - tokensExpired?: boolean; - hasRefreshToken?: boolean; - clientRegistered?: boolean; - authorizationCode?: string; - } = {} - ): jest.Mocked => { - const tokens = config.hasTokens - ? { - access_token: config.tokensExpired ? 'expired-token' : 'valid-token', - token_type: 'Bearer' as const, - ...(config.hasRefreshToken && { refresh_token: 'refresh-token' }) - } - : undefined; - - const clientInfo = config.clientRegistered - ? { - client_id: 'test-client-id', - client_secret: 'test-client-secret' - } - : undefined; - - return { - get redirectUrl() { - return 'http://localhost/callback'; - }, - get clientMetadata() { - return { - redirect_uris: ['http://localhost/callback'], - client_name: 'Test Client' - }; - }, - clientInformation: jest.fn().mockResolvedValue(clientInfo), - tokens: jest.fn().mockResolvedValue(tokens), - saveTokens: jest.fn(), - redirectToAuthorization: jest.fn(), - saveCodeVerifier: jest.fn(), - codeVerifier: jest.fn().mockResolvedValue('test-verifier'), - invalidateCredentials: jest.fn() - }; - }; - - const createCustomFetchMockAuthServer = async () => { - authServer = createServer((req, res) => { - if (req.url === '/.well-known/oauth-authorization-server') { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end( - JSON.stringify({ - issuer: `http://127.0.0.1:${(authServer.address() as AddressInfo).port}`, - authorization_endpoint: `http://127.0.0.1:${(authServer.address() as AddressInfo).port}/authorize`, - token_endpoint: `http://127.0.0.1:${(authServer.address() as AddressInfo).port}/token`, - registration_endpoint: `http://127.0.0.1:${(authServer.address() as AddressInfo).port}/register`, - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - ); - return; - } - - if (req.url === '/token' && req.method === 'POST') { - // Handle token exchange request - let body = ''; - req.on('data', chunk => { - body += chunk; - }); - req.on('end', () => { - const params = new URLSearchParams(body); - if ( - params.get('grant_type') === 'authorization_code' && - params.get('code') === 'test-auth-code' && - params.get('client_id') === 'test-client-id' - ) { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end( - JSON.stringify({ - access_token: 'new-access-token', - token_type: 'Bearer', - expires_in: 3600, - refresh_token: 'new-refresh-token' - }) - ); - } else { - res.writeHead(400).end(); - } - }); - return; - } - - res.writeHead(404).end(); - }); - - // Start auth server on random port - await new Promise(resolve => { - authServer.listen(0, '127.0.0.1', () => { - const addr = authServer.address() as AddressInfo; - authBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - }; - - const createCustomFetchMockResourceServer = async () => { - // Set up resource server that provides OAuth metadata - resourceServer = createServer((req, res) => { - lastServerRequest = req; - - if (req.url === '/.well-known/oauth-protected-resource') { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end( - JSON.stringify({ - resource: resourceBaseUrl.href, - authorization_servers: [authBaseUrl.href] - }) - ); - return; - } - - resourceServerHandler(req, res); - }); - - // Start resource server on random port - await new Promise(resolve => { - resourceServer.listen(0, '127.0.0.1', () => { - const addr = resourceServer.address() as AddressInfo; - resourceBaseUrl = new URL(`http://127.0.0.1:${addr.port}`); - resolve(); - }); - }); - }; - - beforeEach(async () => { - // Close existing servers to set up custom auth flow servers - resourceServer.close(); - authServer.close(); - - const originalFetch = fetch; - - // Create custom fetch spy that delegates to real fetch - customFetch = jest.fn((url, init) => { - return originalFetch(url.toString(), init); - }); - - // Spy on global fetch to detect unauthorized usage - globalFetchSpy = jest.spyOn(global, 'fetch'); - - // Create mock auth provider with default configuration - mockAuthProvider = createMockAuthProvider({ - hasTokens: false, - clientRegistered: true - }); - - // Set up auth server that handles OAuth discovery and token requests - await createCustomFetchMockAuthServer(); - - // Set up resource server - resourceServerHandler = jest.fn( - ( - _req: IncomingMessage, - res: ServerResponse & { - req: IncomingMessage; - } - ) => { - res.writeHead(404).end(); - } - ); - await createCustomFetchMockResourceServer(); - }); - - afterEach(() => { - globalFetchSpy.mockRestore(); - }); - - it('uses custom fetch during auth flow on SSE connection 401 - no global fetch fallback', async () => { - // Set up resource server that returns 401 on SSE connection and provides OAuth metadata - resourceServerHandler.mockImplementation((req, res) => { - if (req.url === '/') { - // Return 401 to trigger auth flow - res.writeHead(401, { - 'WWW-Authenticate': `Bearer realm="mcp", resource_metadata="${resourceBaseUrl.href}.well-known/oauth-protected-resource"` - }); - res.end(); - return; - } - - res.writeHead(404).end(); - }); - - // Create transport with custom fetch and auth provider - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider, - fetch: customFetch - }); - - // Attempt to start - should trigger auth flow and eventually fail with UnauthorizedError - await expect(transport.start()).rejects.toThrow(UnauthorizedError); - - // Verify custom fetch was used - expect(customFetch).toHaveBeenCalled(); - - // Verify specific OAuth endpoints were called with custom fetch - const customFetchCalls = customFetch.mock.calls; - const callUrls = customFetchCalls.map(([url]) => url.toString()); - - // Should have called resource metadata discovery - expect(callUrls.some(url => url.includes('/.well-known/oauth-protected-resource'))).toBe(true); - - // Should have called OAuth authorization server metadata discovery - expect(callUrls.some(url => url.includes('/.well-known/oauth-authorization-server'))).toBe(true); - - // Verify auth provider was called to redirect to authorization - expect(mockAuthProvider.redirectToAuthorization).toHaveBeenCalled(); - - // Global fetch should never have been called - expect(globalFetchSpy).not.toHaveBeenCalled(); - }); - - it('uses custom fetch during auth flow on POST request 401 - no global fetch fallback', async () => { - // Set up resource server that accepts SSE connection but returns 401 on POST - resourceServerHandler.mockImplementation((req, res) => { - switch (req.method) { - case 'GET': - if (req.url === '/') { - // Accept SSE connection - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }); - res.write('event: endpoint\n'); - res.write(`data: ${resourceBaseUrl.href}\n\n`); - return; - } - break; - - case 'POST': - if (req.url === '/') { - // Return 401 to trigger auth retry - res.writeHead(401, { - 'WWW-Authenticate': `Bearer realm="mcp", resource_metadata="${resourceBaseUrl.href}.well-known/oauth-protected-resource"` - }); - res.end(); - return; - } - break; - } - - res.writeHead(404).end(); - }); - - // Create transport with custom fetch and auth provider - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: mockAuthProvider, - fetch: customFetch - }); - - // Start the transport (should succeed) - await transport.start(); - - // Send a message that should trigger 401 and auth retry - const message: JSONRPCMessage = { - jsonrpc: '2.0', - id: '1', - method: 'test', - params: {} - }; - - // Attempt to send message - should trigger auth flow and eventually fail - await expect(transport.send(message)).rejects.toThrow(UnauthorizedError); - - // Verify custom fetch was used - expect(customFetch).toHaveBeenCalled(); - - // Verify specific OAuth endpoints were called with custom fetch - const customFetchCalls = customFetch.mock.calls; - const callUrls = customFetchCalls.map(([url]) => url.toString()); - - // Should have called resource metadata discovery - expect(callUrls.some(url => url.includes('/.well-known/oauth-protected-resource'))).toBe(true); - - // Should have called OAuth authorization server metadata discovery - expect(callUrls.some(url => url.includes('/.well-known/oauth-authorization-server'))).toBe(true); - - // Should have attempted the POST request that triggered the 401 - const postCalls = customFetchCalls.filter( - ([url, options]) => url.toString() === resourceBaseUrl.href && options?.method === 'POST' - ); - expect(postCalls.length).toBeGreaterThan(0); - - // Verify auth provider was called to redirect to authorization - expect(mockAuthProvider.redirectToAuthorization).toHaveBeenCalled(); - - // Global fetch should never have been called - expect(globalFetchSpy).not.toHaveBeenCalled(); - }); - - it('uses custom fetch in finishAuth method - no global fetch fallback', async () => { - // Create mock auth provider that expects to save tokens - const authProviderWithCode = createMockAuthProvider({ - clientRegistered: true, - authorizationCode: 'test-auth-code' - }); - - // Create transport with custom fetch and auth provider - transport = new SSEClientTransport(resourceBaseUrl, { - authProvider: authProviderWithCode, - fetch: customFetch - }); - - // Call finishAuth with authorization code - await transport.finishAuth('test-auth-code'); - - // Verify custom fetch was used - expect(customFetch).toHaveBeenCalled(); - - // Verify specific OAuth endpoints were called with custom fetch - const customFetchCalls = customFetch.mock.calls; - const callUrls = customFetchCalls.map(([url]) => url.toString()); - - // Should have called resource metadata discovery - expect(callUrls.some(url => url.includes('/.well-known/oauth-protected-resource'))).toBe(true); - - // Should have called OAuth authorization server metadata discovery - expect(callUrls.some(url => url.includes('/.well-known/oauth-authorization-server'))).toBe(true); - - // Should have called token endpoint for authorization code exchange - const tokenCalls = customFetchCalls.filter(([url, options]) => url.toString().includes('/token') && options?.method === 'POST'); - expect(tokenCalls.length).toBeGreaterThan(0); - - // Verify tokens were saved - expect(authProviderWithCode.saveTokens).toHaveBeenCalledWith({ - access_token: 'new-access-token', - token_type: 'Bearer', - expires_in: 3600, - refresh_token: 'new-refresh-token' - }); - - // Global fetch should never have been called - expect(globalFetchSpy).not.toHaveBeenCalled(); - }); - }); -}); diff --git a/typescript-sdk/src/client/sse.ts b/typescript-sdk/src/client/sse.ts deleted file mode 100644 index aa49424..0000000 --- a/typescript-sdk/src/client/sse.ts +++ /dev/null @@ -1,275 +0,0 @@ -import { EventSource, type ErrorEvent, type EventSourceInit } from 'eventsource'; -import { Transport, FetchLike } from '../shared/transport.js'; -import { JSONRPCMessage, JSONRPCMessageSchema } from '../types.js'; -import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from './auth.js'; - -export class SseError extends Error { - constructor( - public readonly code: number | undefined, - message: string | undefined, - public readonly event: ErrorEvent - ) { - super(`SSE error: ${message}`); - } -} - -/** - * Configuration options for the `SSEClientTransport`. - */ -export type SSEClientTransportOptions = { - /** - * An OAuth client provider to use for authentication. - * - * When an `authProvider` is specified and the SSE connection is started: - * 1. The connection is attempted with any existing access token from the `authProvider`. - * 2. If the access token has expired, the `authProvider` is used to refresh the token. - * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. - * - * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `SSEClientTransport.finishAuth` with the authorization code before retrying the connection. - * - * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. - * - * `UnauthorizedError` might also be thrown when sending any message over the SSE transport, indicating that the session has expired, and needs to be re-authed and reconnected. - */ - authProvider?: OAuthClientProvider; - - /** - * Customizes the initial SSE request to the server (the request that begins the stream). - * - * NOTE: Setting this property will prevent an `Authorization` header from - * being automatically attached to the SSE request, if an `authProvider` is - * also given. This can be worked around by setting the `Authorization` header - * manually. - */ - eventSourceInit?: EventSourceInit; - - /** - * Customizes recurring POST requests to the server. - */ - requestInit?: RequestInit; - - /** - * Custom fetch implementation used for all network requests. - */ - fetch?: FetchLike; -}; - -/** - * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving - * messages and make separate POST requests for sending messages. - */ -export class SSEClientTransport implements Transport { - private _eventSource?: EventSource; - private _endpoint?: URL; - private _abortController?: AbortController; - private _url: URL; - private _resourceMetadataUrl?: URL; - private _eventSourceInit?: EventSourceInit; - private _requestInit?: RequestInit; - private _authProvider?: OAuthClientProvider; - private _fetch?: FetchLike; - private _protocolVersion?: string; - - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - - constructor(url: URL, opts?: SSEClientTransportOptions) { - this._url = url; - this._resourceMetadataUrl = undefined; - this._eventSourceInit = opts?.eventSourceInit; - this._requestInit = opts?.requestInit; - this._authProvider = opts?.authProvider; - this._fetch = opts?.fetch; - } - - private async _authThenStart(): Promise { - if (!this._authProvider) { - throw new UnauthorizedError('No auth provider'); - } - - let result: AuthResult; - try { - result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - fetchFn: this._fetch - }); - } catch (error) { - this.onerror?.(error as Error); - throw error; - } - - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(); - } - - return await this._startOrAuth(); - } - - private async _commonHeaders(): Promise { - const headers: HeadersInit = {}; - if (this._authProvider) { - const tokens = await this._authProvider.tokens(); - if (tokens) { - headers['Authorization'] = `Bearer ${tokens.access_token}`; - } - } - if (this._protocolVersion) { - headers['mcp-protocol-version'] = this._protocolVersion; - } - - return new Headers({ ...headers, ...this._requestInit?.headers }); - } - - private _startOrAuth(): Promise { - const fetchImpl = (this?._eventSourceInit?.fetch ?? this._fetch ?? fetch) as typeof fetch; - return new Promise((resolve, reject) => { - this._eventSource = new EventSource(this._url.href, { - ...this._eventSourceInit, - fetch: async (url, init) => { - const headers = await this._commonHeaders(); - headers.set('Accept', 'text/event-stream'); - const response = await fetchImpl(url, { - ...init, - headers - }); - - if (response.status === 401 && response.headers.has('www-authenticate')) { - this._resourceMetadataUrl = extractResourceMetadataUrl(response); - } - - return response; - } - }); - this._abortController = new AbortController(); - - this._eventSource.onerror = event => { - if (event.code === 401 && this._authProvider) { - this._authThenStart().then(resolve, reject); - return; - } - - const error = new SseError(event.code, event.message, event); - reject(error); - this.onerror?.(error); - }; - - this._eventSource.onopen = () => { - // The connection is open, but we need to wait for the endpoint to be received. - }; - - this._eventSource.addEventListener('endpoint', (event: Event) => { - const messageEvent = event as MessageEvent; - - try { - this._endpoint = new URL(messageEvent.data, this._url); - if (this._endpoint.origin !== this._url.origin) { - throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); - } - } catch (error) { - reject(error); - this.onerror?.(error as Error); - - void this.close(); - return; - } - - resolve(); - }); - - this._eventSource.onmessage = (event: Event) => { - const messageEvent = event as MessageEvent; - let message: JSONRPCMessage; - try { - message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); - } catch (error) { - this.onerror?.(error as Error); - return; - } - - this.onmessage?.(message); - }; - }); - } - - async start() { - if (this._eventSource) { - throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.'); - } - - return await this._startOrAuth(); - } - - /** - * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. - */ - async finishAuth(authorizationCode: string): Promise { - if (!this._authProvider) { - throw new UnauthorizedError('No auth provider'); - } - - const result = await auth(this._authProvider, { - serverUrl: this._url, - authorizationCode, - resourceMetadataUrl: this._resourceMetadataUrl, - fetchFn: this._fetch - }); - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError('Failed to authorize'); - } - } - - async close(): Promise { - this._abortController?.abort(); - this._eventSource?.close(); - this.onclose?.(); - } - - async send(message: JSONRPCMessage): Promise { - if (!this._endpoint) { - throw new Error('Not connected'); - } - - try { - const headers = await this._commonHeaders(); - headers.set('content-type', 'application/json'); - const init = { - ...this._requestInit, - method: 'POST', - headers, - body: JSON.stringify(message), - signal: this._abortController?.signal - }; - - const response = await (this._fetch ?? fetch)(this._endpoint, init); - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - this._resourceMetadataUrl = extractResourceMetadataUrl(response); - - const result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - fetchFn: this._fetch - }); - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(); - } - - // Purposely _not_ awaited, so we don't call onerror twice - return this.send(message); - } - - const text = await response.text().catch(() => null); - throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); - } - } catch (error) { - this.onerror?.(error as Error); - throw error; - } - } - - setProtocolVersion(version: string): void { - this._protocolVersion = version; - } -} diff --git a/typescript-sdk/src/client/stdio.test.ts b/typescript-sdk/src/client/stdio.test.ts deleted file mode 100644 index d2f5b5c..0000000 --- a/typescript-sdk/src/client/stdio.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { JSONRPCMessage } from '../types.js'; -import { StdioClientTransport, StdioServerParameters } from './stdio.js'; - -// Configure default server parameters based on OS -// Uses 'more' command for Windows and 'tee' command for Unix/Linux -const getDefaultServerParameters = (): StdioServerParameters => { - if (process.platform === 'win32') { - return { command: 'more' }; - } - return { command: '/usr/bin/tee' }; -}; - -const serverParameters = getDefaultServerParameters(); - -test('should start then close cleanly', async () => { - const client = new StdioClientTransport(serverParameters); - client.onerror = error => { - throw error; - }; - - let didClose = false; - client.onclose = () => { - didClose = true; - }; - - await client.start(); - expect(didClose).toBeFalsy(); - await client.close(); - expect(didClose).toBeTruthy(); -}); - -test('should read messages', async () => { - const client = new StdioClientTransport(serverParameters); - client.onerror = error => { - throw error; - }; - - const messages: JSONRPCMessage[] = [ - { - jsonrpc: '2.0', - id: 1, - method: 'ping' - }, - { - jsonrpc: '2.0', - method: 'notifications/initialized' - } - ]; - - const readMessages: JSONRPCMessage[] = []; - const finished = new Promise(resolve => { - client.onmessage = message => { - readMessages.push(message); - - if (JSON.stringify(message) === JSON.stringify(messages[1])) { - resolve(); - } - }; - }); - - await client.start(); - await client.send(messages[0]); - await client.send(messages[1]); - await finished; - expect(readMessages).toEqual(messages); - - await client.close(); -}); - -test('should return child process pid', async () => { - const client = new StdioClientTransport(serverParameters); - - await client.start(); - expect(client.pid).not.toBeNull(); - await client.close(); - expect(client.pid).toBeNull(); -}); diff --git a/typescript-sdk/src/client/stdio.ts b/typescript-sdk/src/client/stdio.ts deleted file mode 100644 index d62a3ae..0000000 --- a/typescript-sdk/src/client/stdio.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { ChildProcess, IOType } from 'node:child_process'; -import spawn from 'cross-spawn'; -import process from 'node:process'; -import { Stream, PassThrough } from 'node:stream'; -import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; -import { Transport } from '../shared/transport.js'; -import { JSONRPCMessage } from '../types.js'; - -export type StdioServerParameters = { - /** - * The executable to run to start the server. - */ - command: string; - - /** - * Command line arguments to pass to the executable. - */ - args?: string[]; - - /** - * The environment to use when spawning the process. - * - * If not specified, the result of getDefaultEnvironment() will be used. - */ - env?: Record; - - /** - * How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`. - * - * The default is "inherit", meaning messages to stderr will be printed to the parent process's stderr. - */ - stderr?: IOType | Stream | number; - - /** - * The working directory to use when spawning the process. - * - * If not specified, the current working directory will be inherited. - */ - cwd?: string; -}; - -/** - * Environment variables to inherit by default, if an environment is not explicitly given. - */ -export const DEFAULT_INHERITED_ENV_VARS = - process.platform === 'win32' - ? [ - 'APPDATA', - 'HOMEDRIVE', - 'HOMEPATH', - 'LOCALAPPDATA', - 'PATH', - 'PROCESSOR_ARCHITECTURE', - 'SYSTEMDRIVE', - 'SYSTEMROOT', - 'TEMP', - 'USERNAME', - 'USERPROFILE', - 'PROGRAMFILES' - ] - : /* list inspired by the default env inheritance of sudo */ - ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER']; - -/** - * Returns a default environment object including only environment variables deemed safe to inherit. - */ -export function getDefaultEnvironment(): Record { - const env: Record = {}; - - for (const key of DEFAULT_INHERITED_ENV_VARS) { - const value = process.env[key]; - if (value === undefined) { - continue; - } - - if (value.startsWith('()')) { - // Skip functions, which are a security risk. - continue; - } - - env[key] = value; - } - - return env; -} - -/** - * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. - * - * This transport is only available in Node.js environments. - */ -export class StdioClientTransport implements Transport { - private _process?: ChildProcess; - private _abortController: AbortController = new AbortController(); - private _readBuffer: ReadBuffer = new ReadBuffer(); - private _serverParams: StdioServerParameters; - private _stderrStream: PassThrough | null = null; - - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - - constructor(server: StdioServerParameters) { - this._serverParams = server; - if (server.stderr === 'pipe' || server.stderr === 'overlapped') { - this._stderrStream = new PassThrough(); - } - } - - /** - * Starts the server process and prepares to communicate with it. - */ - async start(): Promise { - if (this._process) { - throw new Error( - 'StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.' - ); - } - - return new Promise((resolve, reject) => { - this._process = spawn(this._serverParams.command, this._serverParams.args ?? [], { - // merge default env with server env because mcp server needs some env vars - env: { - ...getDefaultEnvironment(), - ...this._serverParams.env - }, - stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'], - shell: false, - signal: this._abortController.signal, - windowsHide: process.platform === 'win32' && isElectron(), - cwd: this._serverParams.cwd - }); - - this._process.on('error', error => { - if (error.name === 'AbortError') { - // Expected when close() is called. - this.onclose?.(); - return; - } - - reject(error); - this.onerror?.(error); - }); - - this._process.on('spawn', () => { - resolve(); - }); - - this._process.on('close', _code => { - this._process = undefined; - this.onclose?.(); - }); - - this._process.stdin?.on('error', error => { - this.onerror?.(error); - }); - - this._process.stdout?.on('data', chunk => { - this._readBuffer.append(chunk); - this.processReadBuffer(); - }); - - this._process.stdout?.on('error', error => { - this.onerror?.(error); - }); - - if (this._stderrStream && this._process.stderr) { - this._process.stderr.pipe(this._stderrStream); - } - }); - } - - /** - * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". - * - * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to - * attach listeners before the start method is invoked. This prevents loss of any early - * error output emitted by the child process. - */ - get stderr(): Stream | null { - if (this._stderrStream) { - return this._stderrStream; - } - - return this._process?.stderr ?? null; - } - - /** - * The child process pid spawned by this transport. - * - * This is only available after the transport has been started. - */ - get pid(): number | null { - return this._process?.pid ?? null; - } - - private processReadBuffer() { - while (true) { - try { - const message = this._readBuffer.readMessage(); - if (message === null) { - break; - } - - this.onmessage?.(message); - } catch (error) { - this.onerror?.(error as Error); - } - } - } - - async close(): Promise { - this._abortController.abort(); - this._process = undefined; - this._readBuffer.clear(); - } - - send(message: JSONRPCMessage): Promise { - return new Promise(resolve => { - if (!this._process?.stdin) { - throw new Error('Not connected'); - } - - const json = serializeMessage(message); - if (this._process.stdin.write(json)) { - resolve(); - } else { - this._process.stdin.once('drain', resolve); - } - }); - } -} - -function isElectron() { - return 'type' in process; -} diff --git a/typescript-sdk/src/client/streamableHttp.test.ts b/typescript-sdk/src/client/streamableHttp.test.ts deleted file mode 100644 index 3c6a9ec..0000000 --- a/typescript-sdk/src/client/streamableHttp.test.ts +++ /dev/null @@ -1,1076 +0,0 @@ -import { StartSSEOptions, StreamableHTTPClientTransport, StreamableHTTPReconnectionOptions } from './streamableHttp.js'; -import { OAuthClientProvider, UnauthorizedError } from './auth.js'; -import { JSONRPCMessage, JSONRPCRequest } from '../types.js'; -import { InvalidClientError, InvalidGrantError, UnauthorizedClientError } from '../server/auth/errors.js'; - -describe('StreamableHTTPClientTransport', () => { - let transport: StreamableHTTPClientTransport; - let mockAuthProvider: jest.Mocked; - - beforeEach(() => { - mockAuthProvider = { - get redirectUrl() { - return 'http://localhost/callback'; - }, - get clientMetadata() { - return { redirect_uris: ['http://localhost/callback'] }; - }, - clientInformation: jest.fn(() => ({ client_id: 'test-client-id', client_secret: 'test-client-secret' })), - tokens: jest.fn(), - saveTokens: jest.fn(), - redirectToAuthorization: jest.fn(), - saveCodeVerifier: jest.fn(), - codeVerifier: jest.fn(), - invalidateCredentials: jest.fn() - }; - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), { authProvider: mockAuthProvider }); - jest.spyOn(global, 'fetch'); - }); - - afterEach(async () => { - await transport.close().catch(() => {}); - jest.clearAllMocks(); - }); - - it('should send JSON-RPC messages via POST', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - params: {}, - id: 'test-id' - }; - - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 202, - headers: new Headers() - }); - - await transport.send(message); - - expect(global.fetch).toHaveBeenCalledWith( - expect.anything(), - expect.objectContaining({ - method: 'POST', - headers: expect.any(Headers), - body: JSON.stringify(message) - }) - ); - }); - - it('should send batch messages', async () => { - const messages: JSONRPCMessage[] = [ - { jsonrpc: '2.0', method: 'test1', params: {}, id: 'id1' }, - { jsonrpc: '2.0', method: 'test2', params: {}, id: 'id2' } - ]; - - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream' }), - body: null - }); - - await transport.send(messages); - - expect(global.fetch).toHaveBeenCalledWith( - expect.anything(), - expect.objectContaining({ - method: 'POST', - headers: expect.any(Headers), - body: JSON.stringify(messages) - }) - ); - }); - - it('should store session ID received during initialization', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'initialize', - params: { - clientInfo: { name: 'test-client', version: '1.0' }, - protocolVersion: '2025-03-26' - }, - id: 'init-id' - }; - - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream', 'mcp-session-id': 'test-session-id' }) - }); - - await transport.send(message); - - // Send a second message that should include the session ID - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 202, - headers: new Headers() - }); - - await transport.send({ jsonrpc: '2.0', method: 'test', params: {} } as JSONRPCMessage); - - // Check that second request included session ID header - const calls = (global.fetch as jest.Mock).mock.calls; - const lastCall = calls[calls.length - 1]; - expect(lastCall[1].headers).toBeDefined(); - expect(lastCall[1].headers.get('mcp-session-id')).toBe('test-session-id'); - }); - - it('should terminate session with DELETE request', async () => { - // First, simulate getting a session ID - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'initialize', - params: { - clientInfo: { name: 'test-client', version: '1.0' }, - protocolVersion: '2025-03-26' - }, - id: 'init-id' - }; - - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream', 'mcp-session-id': 'test-session-id' }) - }); - - await transport.send(message); - expect(transport.sessionId).toBe('test-session-id'); - - // Now terminate the session - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers() - }); - - await transport.terminateSession(); - - // Verify the DELETE request was sent with the session ID - const calls = (global.fetch as jest.Mock).mock.calls; - const lastCall = calls[calls.length - 1]; - expect(lastCall[1].method).toBe('DELETE'); - expect(lastCall[1].headers.get('mcp-session-id')).toBe('test-session-id'); - - // The session ID should be cleared after successful termination - expect(transport.sessionId).toBeUndefined(); - }); - - it("should handle 405 response when server doesn't support session termination", async () => { - // First, simulate getting a session ID - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'initialize', - params: { - clientInfo: { name: 'test-client', version: '1.0' }, - protocolVersion: '2025-03-26' - }, - id: 'init-id' - }; - - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream', 'mcp-session-id': 'test-session-id' }) - }); - - await transport.send(message); - - // Now terminate the session, but server responds with 405 - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: false, - status: 405, - statusText: 'Method Not Allowed', - headers: new Headers() - }); - - await expect(transport.terminateSession()).resolves.not.toThrow(); - }); - - it('should handle 404 response when session expires', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - params: {}, - id: 'test-id' - }; - - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: false, - status: 404, - statusText: 'Not Found', - text: () => Promise.resolve('Session not found'), - headers: new Headers() - }); - - const errorSpy = jest.fn(); - transport.onerror = errorSpy; - - await expect(transport.send(message)).rejects.toThrow('Error POSTing to endpoint (HTTP 404)'); - expect(errorSpy).toHaveBeenCalled(); - }); - - it('should handle non-streaming JSON response', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - params: {}, - id: 'test-id' - }; - - const responseMessage: JSONRPCMessage = { - jsonrpc: '2.0', - result: { success: true }, - id: 'test-id' - }; - - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'application/json' }), - json: () => Promise.resolve(responseMessage) - }); - - const messageSpy = jest.fn(); - transport.onmessage = messageSpy; - - await transport.send(message); - - expect(messageSpy).toHaveBeenCalledWith(responseMessage); - }); - - it('should attempt initial GET connection and handle 405 gracefully', async () => { - // Mock the server not supporting GET for SSE (returning 405) - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: false, - status: 405, - statusText: 'Method Not Allowed' - }); - - // We expect the 405 error to be caught and handled gracefully - // This should not throw an error that breaks the transport - await transport.start(); - await expect(transport['_startOrAuthSse']({})).resolves.not.toThrow('Failed to open SSE stream: Method Not Allowed'); - // Check that GET was attempted - expect(global.fetch).toHaveBeenCalledWith( - expect.anything(), - expect.objectContaining({ - method: 'GET', - headers: expect.any(Headers) - }) - ); - - // Verify transport still works after 405 - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 202, - headers: new Headers() - }); - - await transport.send({ jsonrpc: '2.0', method: 'test', params: {} } as JSONRPCMessage); - expect(global.fetch).toHaveBeenCalledTimes(2); - }); - - it('should handle successful initial GET connection for SSE', async () => { - // Set up readable stream for SSE events - const encoder = new TextEncoder(); - const stream = new ReadableStream({ - start(controller) { - // Send a server notification via SSE - const event = 'event: message\ndata: {"jsonrpc": "2.0", "method": "serverNotification", "params": {}}\n\n'; - controller.enqueue(encoder.encode(event)); - } - }); - - // Mock successful GET connection - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream' }), - body: stream - }); - - const messageSpy = jest.fn(); - transport.onmessage = messageSpy; - - await transport.start(); - await transport['_startOrAuthSse']({}); - - // Give time for the SSE event to be processed - await new Promise(resolve => setTimeout(resolve, 50)); - - expect(messageSpy).toHaveBeenCalledWith( - expect.objectContaining({ - jsonrpc: '2.0', - method: 'serverNotification', - params: {} - }) - ); - }); - - it('should handle multiple concurrent SSE streams', async () => { - // Mock two POST requests that return SSE streams - const makeStream = (id: string) => { - const encoder = new TextEncoder(); - return new ReadableStream({ - start(controller) { - const event = `event: message\ndata: {"jsonrpc": "2.0", "result": {"id": "${id}"}, "id": "${id}"}\n\n`; - controller.enqueue(encoder.encode(event)); - } - }); - }; - - (global.fetch as jest.Mock) - .mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream' }), - body: makeStream('request1') - }) - .mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream' }), - body: makeStream('request2') - }); - - const messageSpy = jest.fn(); - transport.onmessage = messageSpy; - - // Send two concurrent requests - await Promise.all([ - transport.send({ jsonrpc: '2.0', method: 'test1', params: {}, id: 'request1' }), - transport.send({ jsonrpc: '2.0', method: 'test2', params: {}, id: 'request2' }) - ]); - - // Give time for SSE processing - await new Promise(resolve => setTimeout(resolve, 100)); - - // Both streams should have delivered their messages - expect(messageSpy).toHaveBeenCalledTimes(2); - - // Verify received messages without assuming specific order - expect( - messageSpy.mock.calls.some(call => { - const msg = call[0]; - return msg.id === 'request1' && msg.result?.id === 'request1'; - }) - ).toBe(true); - - expect( - messageSpy.mock.calls.some(call => { - const msg = call[0]; - return msg.id === 'request2' && msg.result?.id === 'request2'; - }) - ).toBe(true); - }); - - it('should support custom reconnection options', () => { - // Create a transport with custom reconnection options - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), { - reconnectionOptions: { - initialReconnectionDelay: 500, - maxReconnectionDelay: 10000, - reconnectionDelayGrowFactor: 2, - maxRetries: 5 - } - }); - - // Verify options were set correctly (checking implementation details) - // Access private properties for testing - const transportInstance = transport as unknown as { - _reconnectionOptions: StreamableHTTPReconnectionOptions; - }; - expect(transportInstance._reconnectionOptions.initialReconnectionDelay).toBe(500); - expect(transportInstance._reconnectionOptions.maxRetries).toBe(5); - }); - - it('should pass lastEventId when reconnecting', async () => { - // Create a fresh transport - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp')); - - // Mock fetch to verify headers sent - const fetchSpy = global.fetch as jest.Mock; - fetchSpy.mockReset(); - fetchSpy.mockResolvedValue({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream' }), - body: new ReadableStream() - }); - - // Call the reconnect method directly with a lastEventId - await transport.start(); - // Type assertion to access private method - const transportWithPrivateMethods = transport as unknown as { - _startOrAuthSse: (options: { resumptionToken?: string }) => Promise; - }; - await transportWithPrivateMethods._startOrAuthSse({ resumptionToken: 'test-event-id' }); - - // Verify fetch was called with the lastEventId header - expect(fetchSpy).toHaveBeenCalled(); - const fetchCall = fetchSpy.mock.calls[0]; - const headers = fetchCall[1].headers; - expect(headers.get('last-event-id')).toBe('test-event-id'); - }); - - it('should throw error when invalid content-type is received', async () => { - // Clear any previous state from other tests - jest.clearAllMocks(); - - // Create a fresh transport instance - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp')); - - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - params: {}, - id: 'test-id' - }; - - const stream = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode('invalid text response')); - controller.close(); - } - }); - - const errorSpy = jest.fn(); - transport.onerror = errorSpy; - - (global.fetch as jest.Mock).mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/plain' }), - body: stream - }); - - await transport.start(); - await expect(transport.send(message)).rejects.toThrow('Unexpected content type: text/plain'); - expect(errorSpy).toHaveBeenCalled(); - }); - - it('uses custom fetch implementation if provided', async () => { - // Create custom fetch - const customFetch = jest - .fn() - .mockResolvedValueOnce(new Response(null, { status: 200, headers: { 'content-type': 'text/event-stream' } })) - .mockResolvedValueOnce(new Response(null, { status: 202 })); - - // Create transport instance - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), { - fetch: customFetch - }); - - await transport.start(); - await (transport as unknown as { _startOrAuthSse: (opts: StartSSEOptions) => Promise })._startOrAuthSse({}); - - await transport.send({ jsonrpc: '2.0', method: 'test', params: {}, id: '1' } as JSONRPCMessage); - - // Verify custom fetch was used - expect(customFetch).toHaveBeenCalled(); - - // Global fetch should never have been called - expect(global.fetch).not.toHaveBeenCalled(); - }); - - it('should always send specified custom headers', async () => { - const requestInit = { - headers: { - 'X-Custom-Header': 'CustomValue' - } - }; - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), { - requestInit: requestInit - }); - - let actualReqInit: RequestInit = {}; - - (global.fetch as jest.Mock).mockImplementation(async (_url, reqInit) => { - actualReqInit = reqInit; - return new Response(null, { status: 200, headers: { 'content-type': 'text/event-stream' } }); - }); - - await transport.start(); - - await transport['_startOrAuthSse']({}); - expect((actualReqInit.headers as Headers).get('x-custom-header')).toBe('CustomValue'); - - requestInit.headers['X-Custom-Header'] = 'SecondCustomValue'; - - await transport.send({ jsonrpc: '2.0', method: 'test', params: {} } as JSONRPCMessage); - expect((actualReqInit.headers as Headers).get('x-custom-header')).toBe('SecondCustomValue'); - - expect(global.fetch).toHaveBeenCalledTimes(2); - }); - - it('should always send specified custom headers (Headers class)', async () => { - const requestInit = { - headers: new Headers({ - 'X-Custom-Header': 'CustomValue' - }) - }; - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), { - requestInit: requestInit - }); - - let actualReqInit: RequestInit = {}; - - (global.fetch as jest.Mock).mockImplementation(async (_url, reqInit) => { - actualReqInit = reqInit; - return new Response(null, { status: 200, headers: { 'content-type': 'text/event-stream' } }); - }); - - await transport.start(); - - await transport['_startOrAuthSse']({}); - expect((actualReqInit.headers as Headers).get('x-custom-header')).toBe('CustomValue'); - - (requestInit.headers as Headers).set('X-Custom-Header', 'SecondCustomValue'); - - await transport.send({ jsonrpc: '2.0', method: 'test', params: {} } as JSONRPCMessage); - expect((actualReqInit.headers as Headers).get('x-custom-header')).toBe('SecondCustomValue'); - - expect(global.fetch).toHaveBeenCalledTimes(2); - }); - - it('should have exponential backoff with configurable maxRetries', () => { - // This test verifies the maxRetries and backoff calculation directly - - // Create transport with specific options for testing - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), { - reconnectionOptions: { - initialReconnectionDelay: 100, - maxReconnectionDelay: 5000, - reconnectionDelayGrowFactor: 2, - maxRetries: 3 - } - }); - - // Get access to the internal implementation - const getDelay = transport['_getNextReconnectionDelay'].bind(transport); - - // First retry - should use initial delay - expect(getDelay(0)).toBe(100); - - // Second retry - should double (2^1 * 100 = 200) - expect(getDelay(1)).toBe(200); - - // Third retry - should double again (2^2 * 100 = 400) - expect(getDelay(2)).toBe(400); - - // Fourth retry - should double again (2^3 * 100 = 800) - expect(getDelay(3)).toBe(800); - - // Tenth retry - should be capped at maxReconnectionDelay - expect(getDelay(10)).toBe(5000); - }); - - it('attempts auth flow on 401 during POST request', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - params: {}, - id: 'test-id' - }; - - (global.fetch as jest.Mock) - .mockResolvedValueOnce({ - ok: false, - status: 401, - statusText: 'Unauthorized', - headers: new Headers() - }) - .mockResolvedValue({ - ok: false, - status: 404 - }); - - await expect(transport.send(message)).rejects.toThrow(UnauthorizedError); - expect(mockAuthProvider.redirectToAuthorization.mock.calls).toHaveLength(1); - }); - - describe('Reconnection Logic', () => { - let transport: StreamableHTTPClientTransport; - - // Use fake timers to control setTimeout and make the test instant. - beforeEach(() => jest.useFakeTimers()); - afterEach(() => jest.useRealTimers()); - - it('should reconnect a GET-initiated notification stream that fails', async () => { - // ARRANGE - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), { - reconnectionOptions: { - initialReconnectionDelay: 10, - maxRetries: 1, - maxReconnectionDelay: 1000, // Ensure it doesn't retry indefinitely - reconnectionDelayGrowFactor: 1 // No exponential backoff for simplicity - } - }); - - const errorSpy = jest.fn(); - transport.onerror = errorSpy; - - const failingStream = new ReadableStream({ - start(controller) { - controller.error(new Error('Network failure')); - } - }); - - const fetchMock = global.fetch as jest.Mock; - // Mock the initial GET request, which will fail. - fetchMock.mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream' }), - body: failingStream - }); - // Mock the reconnection GET request, which will succeed. - fetchMock.mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream' }), - body: new ReadableStream() - }); - - // ACT - await transport.start(); - // Trigger the GET stream directly using the internal method for a clean test. - await transport['_startOrAuthSse']({}); - await jest.advanceTimersByTimeAsync(20); // Trigger reconnection timeout - - // ASSERT - expect(errorSpy).toHaveBeenCalledWith( - expect.objectContaining({ - message: expect.stringContaining('SSE stream disconnected: Error: Network failure') - }) - ); - // THE KEY ASSERTION: A second fetch call proves reconnection was attempted. - expect(fetchMock).toHaveBeenCalledTimes(2); - expect(fetchMock.mock.calls[0][1]?.method).toBe('GET'); - expect(fetchMock.mock.calls[1][1]?.method).toBe('GET'); - }); - - it('should NOT reconnect a POST-initiated stream that fails', async () => { - // ARRANGE - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), { - reconnectionOptions: { - initialReconnectionDelay: 10, - maxRetries: 1, - maxReconnectionDelay: 1000, // Ensure it doesn't retry indefinitely - reconnectionDelayGrowFactor: 1 // No exponential backoff for simplicity - } - }); - - const errorSpy = jest.fn(); - transport.onerror = errorSpy; - - const failingStream = new ReadableStream({ - start(controller) { - controller.error(new Error('Network failure')); - } - }); - - const fetchMock = global.fetch as jest.Mock; - // Mock the POST request. It returns a streaming content-type but a failing body. - fetchMock.mockResolvedValueOnce({ - ok: true, - status: 200, - headers: new Headers({ 'content-type': 'text/event-stream' }), - body: failingStream - }); - - // A dummy request message to trigger the `send` logic. - const requestMessage: JSONRPCRequest = { - jsonrpc: '2.0', - method: 'long_running_tool', - id: 'request-1', - params: {} - }; - - // ACT - await transport.start(); - // Use the public `send` method to initiate a POST that gets a stream response. - await transport.send(requestMessage); - await jest.advanceTimersByTimeAsync(20); // Advance time to check for reconnections - - // ASSERT - expect(errorSpy).toHaveBeenCalledWith( - expect.objectContaining({ - message: expect.stringContaining('SSE stream disconnected: Error: Network failure') - }) - ); - // THE KEY ASSERTION: Fetch was only called ONCE. No reconnection was attempted. - expect(fetchMock).toHaveBeenCalledTimes(1); - expect(fetchMock.mock.calls[0][1]?.method).toBe('POST'); - }); - }); - - it('invalidates all credentials on InvalidClientError during auth', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - params: {}, - id: 'test-id' - }; - - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - refresh_token: 'test-refresh' - }); - - const unauthedResponse = { - ok: false, - status: 401, - statusText: 'Unauthorized', - headers: new Headers() - }; - (global.fetch as jest.Mock) - // Initial connection - .mockResolvedValueOnce(unauthedResponse) - // Resource discovery, path aware - .mockResolvedValueOnce(unauthedResponse) - // Resource discovery, root - .mockResolvedValueOnce(unauthedResponse) - // OAuth metadata discovery - .mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'http://localhost:1234', - authorization_endpoint: 'http://localhost:1234/authorize', - token_endpoint: 'http://localhost:1234/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }) - // Token refresh fails with InvalidClientError - .mockResolvedValueOnce( - Response.json(new InvalidClientError('Client authentication failed').toResponseObject(), { status: 400 }) - ) - // Fallback should fail to complete the flow - .mockResolvedValue({ - ok: false, - status: 404 - }); - - await expect(transport.send(message)).rejects.toThrow(UnauthorizedError); - expect(mockAuthProvider.invalidateCredentials).toHaveBeenCalledWith('all'); - }); - - it('invalidates all credentials on UnauthorizedClientError during auth', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - params: {}, - id: 'test-id' - }; - - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - refresh_token: 'test-refresh' - }); - - const unauthedResponse = { - ok: false, - status: 401, - statusText: 'Unauthorized', - headers: new Headers() - }; - (global.fetch as jest.Mock) - // Initial connection - .mockResolvedValueOnce(unauthedResponse) - // Resource discovery, path aware - .mockResolvedValueOnce(unauthedResponse) - // Resource discovery, root - .mockResolvedValueOnce(unauthedResponse) - // OAuth metadata discovery - .mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'http://localhost:1234', - authorization_endpoint: 'http://localhost:1234/authorize', - token_endpoint: 'http://localhost:1234/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }) - // Token refresh fails with UnauthorizedClientError - .mockResolvedValueOnce(Response.json(new UnauthorizedClientError('Client not authorized').toResponseObject(), { status: 400 })) - // Fallback should fail to complete the flow - .mockResolvedValue({ - ok: false, - status: 404 - }); - - await expect(transport.send(message)).rejects.toThrow(UnauthorizedError); - expect(mockAuthProvider.invalidateCredentials).toHaveBeenCalledWith('all'); - }); - - it('invalidates tokens on InvalidGrantError during auth', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - params: {}, - id: 'test-id' - }; - - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - refresh_token: 'test-refresh' - }); - - const unauthedResponse = { - ok: false, - status: 401, - statusText: 'Unauthorized', - headers: new Headers() - }; - (global.fetch as jest.Mock) - // Initial connection - .mockResolvedValueOnce(unauthedResponse) - // Resource discovery, path aware - .mockResolvedValueOnce(unauthedResponse) - // Resource discovery, root - .mockResolvedValueOnce(unauthedResponse) - // OAuth metadata discovery - .mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'http://localhost:1234', - authorization_endpoint: 'http://localhost:1234/authorize', - token_endpoint: 'http://localhost:1234/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }) - // Token refresh fails with InvalidGrantError - .mockResolvedValueOnce(Response.json(new InvalidGrantError('Invalid refresh token').toResponseObject(), { status: 400 })) - // Fallback should fail to complete the flow - .mockResolvedValue({ - ok: false, - status: 404 - }); - - await expect(transport.send(message)).rejects.toThrow(UnauthorizedError); - expect(mockAuthProvider.invalidateCredentials).toHaveBeenCalledWith('tokens'); - }); - - describe('custom fetch in auth code paths', () => { - it('uses custom fetch during auth flow on 401 - no global fetch fallback', async () => { - const unauthedResponse = { - ok: false, - status: 401, - statusText: 'Unauthorized', - headers: new Headers() - }; - - // Create custom fetch - const customFetch = jest - .fn() - // Initial connection - .mockResolvedValueOnce(unauthedResponse) - // Resource discovery - .mockResolvedValueOnce(unauthedResponse) - // OAuth metadata discovery - .mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'http://localhost:1234', - authorization_endpoint: 'http://localhost:1234/authorize', - token_endpoint: 'http://localhost:1234/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }) - // Token refresh fails with InvalidClientError - .mockResolvedValueOnce( - Response.json(new InvalidClientError('Client authentication failed').toResponseObject(), { status: 400 }) - ) - // Fallback should fail to complete the flow - .mockResolvedValue({ - ok: false, - status: 404 - }); - - // Create transport instance - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), { - authProvider: mockAuthProvider, - fetch: customFetch - }); - - // Attempt to start - should trigger auth flow and eventually fail with UnauthorizedError - await transport.start(); - await expect( - (transport as unknown as { _startOrAuthSse: (opts: StartSSEOptions) => Promise })._startOrAuthSse({}) - ).rejects.toThrow(UnauthorizedError); - - // Verify custom fetch was used - expect(customFetch).toHaveBeenCalled(); - - // Verify specific OAuth endpoints were called with custom fetch - const customFetchCalls = customFetch.mock.calls; - const callUrls = customFetchCalls.map(([url]) => url.toString()); - - // Should have called resource metadata discovery - expect(callUrls.some(url => url.includes('/.well-known/oauth-protected-resource'))).toBe(true); - - // Should have called OAuth authorization server metadata discovery - expect(callUrls.some(url => url.includes('/.well-known/oauth-authorization-server'))).toBe(true); - - // Verify auth provider was called to redirect to authorization - expect(mockAuthProvider.redirectToAuthorization).toHaveBeenCalled(); - - // Global fetch should never have been called - expect(global.fetch).not.toHaveBeenCalled(); - }); - - it('uses custom fetch in finishAuth method - no global fetch fallback', async () => { - // Create custom fetch - const customFetch = jest - .fn() - // Protected resource metadata discovery - .mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - authorization_servers: ['http://localhost:1234'], - resource: 'http://localhost:1234/mcp' - }) - }) - // OAuth metadata discovery - .mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'http://localhost:1234', - authorization_endpoint: 'http://localhost:1234/authorize', - token_endpoint: 'http://localhost:1234/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }) - // Code exchange - .mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - access_token: 'new-access-token', - refresh_token: 'new-refresh-token', - token_type: 'Bearer', - expires_in: 3600 - }) - }); - - // Create transport instance - transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), { - authProvider: mockAuthProvider, - fetch: customFetch - }); - - // Call finishAuth with authorization code - await transport.finishAuth('test-auth-code'); - - // Verify custom fetch was used - expect(customFetch).toHaveBeenCalled(); - - // Verify specific OAuth endpoints were called with custom fetch - const customFetchCalls = customFetch.mock.calls; - const callUrls = customFetchCalls.map(([url]) => url.toString()); - - // Should have called resource metadata discovery - expect(callUrls.some(url => url.includes('/.well-known/oauth-protected-resource'))).toBe(true); - - // Should have called OAuth authorization server metadata discovery - expect(callUrls.some(url => url.includes('/.well-known/oauth-authorization-server'))).toBe(true); - - // Should have called token endpoint for authorization code exchange - const tokenCalls = customFetchCalls.filter(([url, options]) => url.toString().includes('/token') && options?.method === 'POST'); - expect(tokenCalls.length).toBeGreaterThan(0); - - // Verify tokens were saved - expect(mockAuthProvider.saveTokens).toHaveBeenCalledWith({ - access_token: 'new-access-token', - token_type: 'Bearer', - expires_in: 3600, - refresh_token: 'new-refresh-token' - }); - - // Global fetch should never have been called - expect(global.fetch).not.toHaveBeenCalled(); - }); - }); - - describe('prevent infinite recursion when server returns 401 after successful auth', () => { - it('should throw error when server returns 401 after successful auth', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - params: {}, - id: 'test-id' - }; - - // Mock provider with refresh token to enable token refresh flow - mockAuthProvider.tokens.mockResolvedValue({ - access_token: 'test-token', - token_type: 'Bearer', - refresh_token: 'refresh-token' - }); - - const unauthedResponse = { - ok: false, - status: 401, - statusText: 'Unauthorized', - headers: new Headers() - }; - - (global.fetch as jest.Mock) - // First request - 401, triggers auth flow - .mockResolvedValueOnce(unauthedResponse) - // Resource discovery, path aware - .mockResolvedValueOnce(unauthedResponse) - // Resource discovery, root - .mockResolvedValueOnce(unauthedResponse) - // OAuth metadata discovery - .mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - issuer: 'http://localhost:1234', - authorization_endpoint: 'http://localhost:1234/authorize', - token_endpoint: 'http://localhost:1234/token', - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'] - }) - }) - // Token refresh succeeds - .mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => ({ - access_token: 'new-access-token', - token_type: 'Bearer', - expires_in: 3600 - }) - }) - // Retry the original request - still 401 (broken server) - .mockResolvedValueOnce(unauthedResponse); - - await expect(transport.send(message)).rejects.toThrow('Server returned 401 after successful authentication'); - expect(mockAuthProvider.saveTokens).toHaveBeenCalledWith({ - access_token: 'new-access-token', - token_type: 'Bearer', - expires_in: 3600, - refresh_token: 'refresh-token' // Refresh token is preserved - }); - }); - }); -}); diff --git a/typescript-sdk/src/client/streamableHttp.ts b/typescript-sdk/src/client/streamableHttp.ts deleted file mode 100644 index 12cb948..0000000 --- a/typescript-sdk/src/client/streamableHttp.ts +++ /dev/null @@ -1,560 +0,0 @@ -import { Transport, FetchLike } from '../shared/transport.js'; -import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessage, JSONRPCMessageSchema } from '../types.js'; -import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from './auth.js'; -import { EventSourceParserStream } from 'eventsource-parser/stream'; - -// Default reconnection options for StreamableHTTP connections -const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconnectionOptions = { - initialReconnectionDelay: 1000, - maxReconnectionDelay: 30000, - reconnectionDelayGrowFactor: 1.5, - maxRetries: 2 -}; - -export class StreamableHTTPError extends Error { - constructor( - public readonly code: number | undefined, - message: string | undefined - ) { - super(`Streamable HTTP error: ${message}`); - } -} - -/** - * Options for starting or authenticating an SSE connection - */ -export interface StartSSEOptions { - /** - * The resumption token used to continue long-running requests that were interrupted. - * - * This allows clients to reconnect and continue from where they left off. - */ - resumptionToken?: string; - - /** - * A callback that is invoked when the resumption token changes. - * - * This allows clients to persist the latest token for potential reconnection. - */ - onresumptiontoken?: (token: string) => void; - - /** - * Override Message ID to associate with the replay message - * so that response can be associate with the new resumed request. - */ - replayMessageId?: string | number; -} - -/** - * Configuration options for reconnection behavior of the StreamableHTTPClientTransport. - */ -export interface StreamableHTTPReconnectionOptions { - /** - * Maximum backoff time between reconnection attempts in milliseconds. - * Default is 30000 (30 seconds). - */ - maxReconnectionDelay: number; - - /** - * Initial backoff time between reconnection attempts in milliseconds. - * Default is 1000 (1 second). - */ - initialReconnectionDelay: number; - - /** - * The factor by which the reconnection delay increases after each attempt. - * Default is 1.5. - */ - reconnectionDelayGrowFactor: number; - - /** - * Maximum number of reconnection attempts before giving up. - * Default is 2. - */ - maxRetries: number; -} - -/** - * Configuration options for the `StreamableHTTPClientTransport`. - */ -export type StreamableHTTPClientTransportOptions = { - /** - * An OAuth client provider to use for authentication. - * - * When an `authProvider` is specified and the connection is started: - * 1. The connection is attempted with any existing access token from the `authProvider`. - * 2. If the access token has expired, the `authProvider` is used to refresh the token. - * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. - * - * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `StreamableHTTPClientTransport.finishAuth` with the authorization code before retrying the connection. - * - * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. - * - * `UnauthorizedError` might also be thrown when sending any message over the transport, indicating that the session has expired, and needs to be re-authed and reconnected. - */ - authProvider?: OAuthClientProvider; - - /** - * Customizes HTTP requests to the server. - */ - requestInit?: RequestInit; - - /** - * Custom fetch implementation used for all network requests. - */ - fetch?: FetchLike; - - /** - * Options to configure the reconnection behavior. - */ - reconnectionOptions?: StreamableHTTPReconnectionOptions; - - /** - * Session ID for the connection. This is used to identify the session on the server. - * When not provided and connecting to a server that supports session IDs, the server will generate a new session ID. - */ - sessionId?: string; -}; - -/** - * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events - * for receiving messages. - */ -export class StreamableHTTPClientTransport implements Transport { - private _abortController?: AbortController; - private _url: URL; - private _resourceMetadataUrl?: URL; - private _requestInit?: RequestInit; - private _authProvider?: OAuthClientProvider; - private _fetch?: FetchLike; - private _sessionId?: string; - private _reconnectionOptions: StreamableHTTPReconnectionOptions; - private _protocolVersion?: string; - private _hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401 - - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - - constructor(url: URL, opts?: StreamableHTTPClientTransportOptions) { - this._url = url; - this._resourceMetadataUrl = undefined; - this._requestInit = opts?.requestInit; - this._authProvider = opts?.authProvider; - this._fetch = opts?.fetch; - this._sessionId = opts?.sessionId; - this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; - } - - private async _authThenStart(): Promise { - if (!this._authProvider) { - throw new UnauthorizedError('No auth provider'); - } - - let result: AuthResult; - try { - result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - fetchFn: this._fetch - }); - } catch (error) { - this.onerror?.(error as Error); - throw error; - } - - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(); - } - - return await this._startOrAuthSse({ resumptionToken: undefined }); - } - - private async _commonHeaders(): Promise { - const headers: HeadersInit & Record = {}; - if (this._authProvider) { - const tokens = await this._authProvider.tokens(); - if (tokens) { - headers['Authorization'] = `Bearer ${tokens.access_token}`; - } - } - - if (this._sessionId) { - headers['mcp-session-id'] = this._sessionId; - } - if (this._protocolVersion) { - headers['mcp-protocol-version'] = this._protocolVersion; - } - - const extraHeaders = this._normalizeHeaders(this._requestInit?.headers); - - return new Headers({ - ...headers, - ...extraHeaders - }); - } - - private async _startOrAuthSse(options: StartSSEOptions): Promise { - const { resumptionToken } = options; - try { - // Try to open an initial SSE stream with GET to listen for server messages - // This is optional according to the spec - server may not support it - const headers = await this._commonHeaders(); - headers.set('Accept', 'text/event-stream'); - - // Include Last-Event-ID header for resumable streams if provided - if (resumptionToken) { - headers.set('last-event-id', resumptionToken); - } - - const response = await (this._fetch ?? fetch)(this._url, { - method: 'GET', - headers, - signal: this._abortController?.signal - }); - - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - // Need to authenticate - return await this._authThenStart(); - } - - // 405 indicates that the server does not offer an SSE stream at GET endpoint - // This is an expected case that should not trigger an error - if (response.status === 405) { - return; - } - - throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); - } - - this._handleSseStream(response.body, options, true); - } catch (error) { - this.onerror?.(error as Error); - throw error; - } - } - - /** - * Calculates the next reconnection delay using backoff algorithm - * - * @param attempt Current reconnection attempt count for the specific stream - * @returns Time to wait in milliseconds before next reconnection attempt - */ - private _getNextReconnectionDelay(attempt: number): number { - // Access default values directly, ensuring they're never undefined - const initialDelay = this._reconnectionOptions.initialReconnectionDelay; - const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; - const maxDelay = this._reconnectionOptions.maxReconnectionDelay; - - // Cap at maximum delay - return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); - } - - private _normalizeHeaders(headers: HeadersInit | undefined): Record { - if (!headers) return {}; - - if (headers instanceof Headers) { - return Object.fromEntries(headers.entries()); - } - - if (Array.isArray(headers)) { - return Object.fromEntries(headers); - } - - return { ...(headers as Record) }; - } - - /** - * Schedule a reconnection attempt with exponential backoff - * - * @param lastEventId The ID of the last received event for resumability - * @param attemptCount Current reconnection attempt count for this specific stream - */ - private _scheduleReconnection(options: StartSSEOptions, attemptCount = 0): void { - // Use provided options or default options - const maxRetries = this._reconnectionOptions.maxRetries; - - // Check if we've exceeded maximum retry attempts - if (maxRetries > 0 && attemptCount >= maxRetries) { - this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); - return; - } - - // Calculate next delay based on current attempt count - const delay = this._getNextReconnectionDelay(attemptCount); - - // Schedule the reconnection - setTimeout(() => { - // Use the last event ID to resume where we left off - this._startOrAuthSse(options).catch(error => { - this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`)); - // Schedule another attempt if this one failed, incrementing the attempt counter - this._scheduleReconnection(options, attemptCount + 1); - }); - }, delay); - } - - private _handleSseStream(stream: ReadableStream | null, options: StartSSEOptions, isReconnectable: boolean): void { - if (!stream) { - return; - } - const { onresumptiontoken, replayMessageId } = options; - - let lastEventId: string | undefined; - const processStream = async () => { - // this is the closest we can get to trying to catch network errors - // if something happens reader will throw - try { - // Create a pipeline: binary stream -> text decoder -> SSE parser - const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).getReader(); - - while (true) { - const { value: event, done } = await reader.read(); - if (done) { - break; - } - - // Update last event ID if provided - if (event.id) { - lastEventId = event.id; - onresumptiontoken?.(event.id); - } - - if (!event.event || event.event === 'message') { - try { - const message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); - if (replayMessageId !== undefined && isJSONRPCResponse(message)) { - message.id = replayMessageId; - } - this.onmessage?.(message); - } catch (error) { - this.onerror?.(error as Error); - } - } - } - } catch (error) { - // Handle stream errors - likely a network disconnect - this.onerror?.(new Error(`SSE stream disconnected: ${error}`)); - - // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing - if (isReconnectable && this._abortController && !this._abortController.signal.aborted) { - // Use the exponential backoff reconnection strategy - try { - this._scheduleReconnection( - { - resumptionToken: lastEventId, - onresumptiontoken, - replayMessageId - }, - 0 - ); - } catch (error) { - this.onerror?.(new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`)); - } - } - } - }; - processStream(); - } - - async start() { - if (this._abortController) { - throw new Error( - 'StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.' - ); - } - - this._abortController = new AbortController(); - } - - /** - * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. - */ - async finishAuth(authorizationCode: string): Promise { - if (!this._authProvider) { - throw new UnauthorizedError('No auth provider'); - } - - const result = await auth(this._authProvider, { - serverUrl: this._url, - authorizationCode, - resourceMetadataUrl: this._resourceMetadataUrl, - fetchFn: this._fetch - }); - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError('Failed to authorize'); - } - } - - async close(): Promise { - // Abort any pending requests - this._abortController?.abort(); - - this.onclose?.(); - } - - async send( - message: JSONRPCMessage | JSONRPCMessage[], - options?: { resumptionToken?: string; onresumptiontoken?: (token: string) => void } - ): Promise { - try { - const { resumptionToken, onresumptiontoken } = options || {}; - - if (resumptionToken) { - // If we have at last event ID, we need to reconnect the SSE stream - this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : undefined }).catch(err => - this.onerror?.(err) - ); - return; - } - - const headers = await this._commonHeaders(); - headers.set('content-type', 'application/json'); - headers.set('accept', 'application/json, text/event-stream'); - - const init = { - ...this._requestInit, - method: 'POST', - headers, - body: JSON.stringify(message), - signal: this._abortController?.signal - }; - - const response = await (this._fetch ?? fetch)(this._url, init); - - // Handle session ID received during initialization - const sessionId = response.headers.get('mcp-session-id'); - if (sessionId) { - this._sessionId = sessionId; - } - - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - // Prevent infinite recursion when server returns 401 after successful auth - if (this._hasCompletedAuthFlow) { - throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication'); - } - - this._resourceMetadataUrl = extractResourceMetadataUrl(response); - - const result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - fetchFn: this._fetch - }); - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(); - } - - // Mark that we completed auth flow - this._hasCompletedAuthFlow = true; - // Purposely _not_ awaited, so we don't call onerror twice - return this.send(message); - } - - const text = await response.text().catch(() => null); - throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); - } - - // Reset auth loop flag on successful response - this._hasCompletedAuthFlow = false; - - // If the response is 202 Accepted, there's no body to process - if (response.status === 202) { - // if the accepted notification is initialized, we start the SSE stream - // if it's supported by the server - if (isInitializedNotification(message)) { - // Start without a lastEventId since this is a fresh connection - this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err)); - } - return; - } - - // Get original message(s) for detecting request IDs - const messages = Array.isArray(message) ? message : [message]; - - const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0; - - // Check the response type - const contentType = response.headers.get('content-type'); - - if (hasRequests) { - if (contentType?.includes('text/event-stream')) { - // Handle SSE stream responses for requests - // We use the same handler as standalone streams, which now supports - // reconnection with the last event ID - this._handleSseStream(response.body, { onresumptiontoken }, false); - } else if (contentType?.includes('application/json')) { - // For non-streaming servers, we might get direct JSON responses - const data = await response.json(); - const responseMessages = Array.isArray(data) - ? data.map(msg => JSONRPCMessageSchema.parse(msg)) - : [JSONRPCMessageSchema.parse(data)]; - - for (const msg of responseMessages) { - this.onmessage?.(msg); - } - } else { - throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`); - } - } - } catch (error) { - this.onerror?.(error as Error); - throw error; - } - } - - get sessionId(): string | undefined { - return this._sessionId; - } - - /** - * Terminates the current session by sending a DELETE request to the server. - * - * Clients that no longer need a particular session - * (e.g., because the user is leaving the client application) SHOULD send an - * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly - * terminate the session. - * - * The server MAY respond with HTTP 405 Method Not Allowed, indicating that - * the server does not allow clients to terminate sessions. - */ - async terminateSession(): Promise { - if (!this._sessionId) { - return; // No session to terminate - } - - try { - const headers = await this._commonHeaders(); - - const init = { - ...this._requestInit, - method: 'DELETE', - headers, - signal: this._abortController?.signal - }; - - const response = await (this._fetch ?? fetch)(this._url, init); - - // We specifically handle 405 as a valid response according to the spec, - // meaning the server does not support explicit session termination - if (!response.ok && response.status !== 405) { - throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); - } - - this._sessionId = undefined; - } catch (error) { - this.onerror?.(error as Error); - throw error; - } - } - - setProtocolVersion(version: string): void { - this._protocolVersion = version; - } - get protocolVersion(): string | undefined { - return this._protocolVersion; - } -} diff --git a/typescript-sdk/src/client/websocket.ts b/typescript-sdk/src/client/websocket.ts deleted file mode 100644 index aed766c..0000000 --- a/typescript-sdk/src/client/websocket.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { Transport } from '../shared/transport.js'; -import { JSONRPCMessage, JSONRPCMessageSchema } from '../types.js'; - -const SUBPROTOCOL = 'mcp'; - -/** - * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. - */ -export class WebSocketClientTransport implements Transport { - private _socket?: WebSocket; - private _url: URL; - - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - - constructor(url: URL) { - this._url = url; - } - - start(): Promise { - if (this._socket) { - throw new Error( - 'WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.' - ); - } - - return new Promise((resolve, reject) => { - this._socket = new WebSocket(this._url, SUBPROTOCOL); - - this._socket.onerror = event => { - const error = 'error' in event ? (event.error as Error) : new Error(`WebSocket error: ${JSON.stringify(event)}`); - reject(error); - this.onerror?.(error); - }; - - this._socket.onopen = () => { - resolve(); - }; - - this._socket.onclose = () => { - this.onclose?.(); - }; - - this._socket.onmessage = (event: MessageEvent) => { - let message: JSONRPCMessage; - try { - message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); - } catch (error) { - this.onerror?.(error as Error); - return; - } - - this.onmessage?.(message); - }; - }); - } - - async close(): Promise { - this._socket?.close(); - } - - send(message: JSONRPCMessage): Promise { - return new Promise((resolve, reject) => { - if (!this._socket) { - reject(new Error('Not connected')); - return; - } - - this._socket?.send(JSON.stringify(message)); - resolve(); - }); - } -} diff --git a/typescript-sdk/src/examples/README.md b/typescript-sdk/src/examples/README.md deleted file mode 100644 index 1c30b8d..0000000 --- a/typescript-sdk/src/examples/README.md +++ /dev/null @@ -1,304 +0,0 @@ -# MCP TypeScript SDK Examples - -This directory contains example implementations of MCP clients and servers using the TypeScript SDK. - -## Table of Contents - -- [Client Implementations](#client-implementations) - - [Streamable HTTP Client](#streamable-http-client) - - [Backwards Compatible Client](#backwards-compatible-client) -- [Server Implementations](#server-implementations) - - [Single Node Deployment](#single-node-deployment) - - [Streamable HTTP Transport](#streamable-http-transport) - - [Deprecated SSE Transport](#deprecated-sse-transport) - - [Backwards Compatible Server](#streamable-http-backwards-compatible-server-with-sse) - - [Multi-Node Deployment](#multi-node-deployment) -- [Backwards Compatibility](#testing-streamable-http-backwards-compatibility-with-sse) - -## Client Implementations - -### Streamable HTTP Client - -A full-featured interactive client that connects to a Streamable HTTP server, demonstrating how to: - -- Establish and manage a connection to an MCP server -- List and call tools with arguments -- Handle notifications through the SSE stream -- List and get prompts with arguments -- List available resources -- Handle session termination and reconnection -- Support for resumability with Last-Event-ID tracking - -```bash -npx tsx src/examples/client/simpleStreamableHttp.ts -``` - -Example client with OAuth: - -```bash -npx tsx src/examples/client/simpleOAuthClient.js -``` - -### Backwards Compatible Client - -A client that implements backwards compatibility according to the [MCP specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#backwards-compatibility), allowing it to work with both new and legacy servers. This client demonstrates: - -- The client first POSTs an initialize request to the server URL: - - If successful, it uses the Streamable HTTP transport - - If it fails with a 4xx status, it attempts a GET request to establish an SSE stream - -```bash -npx tsx src/examples/client/streamableHttpWithSseFallbackClient.ts -``` - -## Server Implementations - -### Single Node Deployment - -These examples demonstrate how to set up an MCP server on a single node with different transport options. - -#### Streamable HTTP Transport - -##### Simple Streamable HTTP Server - -A server that implements the Streamable HTTP transport (protocol version 2025-03-26). - -- Basic server setup with Express and the Streamable HTTP transport -- Session management with an in-memory event store for resumability -- Tool implementation with the `greet` and `multi-greet` tools -- Prompt implementation with the `greeting-template` prompt -- Static resource exposure -- Support for notifications via SSE stream established by GET requests -- Session termination via DELETE requests - -```bash -npx tsx src/examples/server/simpleStreamableHttp.ts - -# To add a demo of authentication to this example, use: -npx tsx src/examples/server/simpleStreamableHttp.ts --oauth - -# To mitigate impersonation risks, enable strict Resource Identifier verification: -npx tsx src/examples/server/simpleStreamableHttp.ts --oauth --oauth-strict -``` - -##### JSON Response Mode Server - -A server that uses Streamable HTTP transport with JSON response mode enabled (no SSE). - -- Streamable HTTP with JSON response mode, which returns responses directly in the response body -- Limited support for notifications (since SSE is disabled) -- Proper response handling according to the MCP specification for servers that don't support SSE -- Returning appropriate HTTP status codes for unsupported methods - -```bash -npx tsx src/examples/server/jsonResponseStreamableHttp.ts -``` - -##### Streamable HTTP with server notifications - -A server that demonstrates server notifications using Streamable HTTP. - -- Resource list change notifications with dynamically added resources -- Automatic resource creation on a timed interval - -```bash -npx tsx src/examples/server/standaloneSseWithGetStreamableHttp.ts -``` - -#### Deprecated SSE Transport - -A server that implements the deprecated HTTP+SSE transport (protocol version 2024-11-05). This example only used for testing backwards compatibility for clients. - -- Two separate endpoints: `/mcp` for the SSE stream (GET) and `/messages` for client messages (POST) -- Tool implementation with a `start-notification-stream` tool that demonstrates sending periodic notifications - -```bash -npx tsx src/examples/server/simpleSseServer.ts -``` - -#### Streamable Http Backwards Compatible Server with SSE - -A server that supports both Streamable HTTP and SSE transports, adhering to the [MCP specification for backwards compatibility](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#backwards-compatibility). - -- Single MCP server instance with multiple transport options -- Support for Streamable HTTP requests at `/mcp` endpoint (GET/POST/DELETE) -- Support for deprecated SSE transport with `/sse` (GET) and `/messages` (POST) -- Session type tracking to avoid mixing transport types -- Notifications and tool execution across both transport types - -```bash -npx tsx src/examples/server/sseAndStreamableHttpCompatibleServer.ts -``` - -### Multi-Node Deployment - -When deploying MCP servers in a horizontally scaled environment (multiple server instances), there are a few different options that can be useful for different use cases: - -- **Stateless mode** - No need to maintain state between calls to MCP servers. Useful for simple API wrapper servers. -- **Persistent storage mode** - No local state needed, but session data is stored in a database. Example: an MCP server for online ordering where the shopping cart is stored in a database. -- **Local state with message routing** - Local state is needed, and all requests for a session must be routed to the correct node. This can be done with a message queue and pub/sub system. - -#### Stateless Mode - -The Streamable HTTP transport can be configured to operate without tracking sessions. This is perfect for simple API proxies or when each request is completely independent. - -##### Implementation - -To enable stateless mode, configure the `StreamableHTTPServerTransport` with: - -```typescript -sessionIdGenerator: undefined; -``` - -This disables session management entirely, and the server won't generate or expect session IDs. - -- No session ID headers are sent or expected -- Any server node can process any request -- No state is preserved between requests -- Perfect for RESTful or stateless API scenarios -- Simplest deployment model with minimal infrastructure requirements - -``` -┌─────────────────────────────────────────────┐ -│ Client │ -└─────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────┐ -│ Load Balancer │ -└─────────────────────────────────────────────┘ - │ │ - ▼ ▼ -┌─────────────────┐ ┌─────────────────────┐ -│ MCP Server #1 │ │ MCP Server #2 │ -│ (Node.js) │ │ (Node.js) │ -└─────────────────┘ └─────────────────────┘ -``` - -#### Persistent Storage Mode - -For cases where you need session continuity but don't need to maintain in-memory state on specific nodes, you can use a database to persist session data while still allowing any node to handle requests. - -##### Implementation - -Configure the transport with session management, but retrieve and store all state in an external persistent storage: - -```typescript -sessionIdGenerator: () => randomUUID(), -eventStore: databaseEventStore -``` - -All session state is stored in the database, and any node can serve any client by retrieving the state when needed. - -- Maintains sessions with unique IDs -- Stores all session data in an external database -- Provides resumability through the database-backed EventStore -- Any node can handle any request for the same session -- No node-specific memory state means no need for message routing -- Good for applications where state can be fully externalized -- Somewhat higher latency due to database access for each request - -``` -┌─────────────────────────────────────────────┐ -│ Client │ -└─────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────┐ -│ Load Balancer │ -└─────────────────────────────────────────────┘ - │ │ - ▼ ▼ -┌─────────────────┐ ┌─────────────────────┐ -│ MCP Server #1 │ │ MCP Server #2 │ -│ (Node.js) │ │ (Node.js) │ -└─────────────────┘ └─────────────────────┘ - │ │ - │ │ - ▼ ▼ -┌─────────────────────────────────────────────┐ -│ Database (PostgreSQL) │ -│ │ -│ • Session state │ -│ • Event storage for resumability │ -└─────────────────────────────────────────────┘ -``` - -#### Streamable HTTP with Distributed Message Routing - -For scenarios where local in-memory state must be maintained on specific nodes (such as Computer Use or complex session state), the Streamable HTTP transport can be combined with a pub/sub system to route messages to the correct node handling each session. - -1. **Bidirectional Message Queue Integration**: - - All nodes both publish to and subscribe from the message queue - - Each node registers the sessions it's actively handling - - Messages are routed based on session ownership - -2. **Request Handling Flow**: - - When a client connects to Node A with an existing `mcp-session-id` - - If Node A doesn't own this session, it: - - Establishes and maintains the SSE connection with the client - - Publishes the request to the message queue with the session ID - - Node B (which owns the session) receives the request from the queue - - Node B processes the request with its local session state - - Node B publishes responses/notifications back to the queue - - Node A subscribes to the response channel and forwards to the client - -3. **Channel Identification**: - - Each message channel combines both `mcp-session-id` and `stream-id` - - This ensures responses are correctly routed back to the originating connection - -``` -┌─────────────────────────────────────────────┐ -│ Client │ -└─────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────┐ -│ Load Balancer │ -└─────────────────────────────────────────────┘ - │ │ - ▼ ▼ -┌─────────────────┐ ┌─────────────────────┐ -│ MCP Server #1 │◄───►│ MCP Server #2 │ -│ (Has Session A) │ │ (Has Session B) │ -└─────────────────┘ └─────────────────────┘ - ▲│ ▲│ - │▼ │▼ -┌─────────────────────────────────────────────┐ -│ Message Queue / Pub-Sub │ -│ │ -│ • Session ownership registry │ -│ • Bidirectional message routing │ -│ • Request/response forwarding │ -└─────────────────────────────────────────────┘ -``` - -- Maintains session affinity for stateful operations without client redirection -- Enables horizontal scaling while preserving complex in-memory state -- Provides fault tolerance through the message queue as intermediary - -## Backwards Compatibility - -### Testing Streamable HTTP Backwards Compatibility with SSE - -To test the backwards compatibility features: - -1. Start one of the server implementations: - - ```bash - # Legacy SSE server (protocol version 2024-11-05) - npx tsx src/examples/server/simpleSseServer.ts - - # Streamable HTTP server (protocol version 2025-03-26) - npx tsx src/examples/server/simpleStreamableHttp.ts - - # Backwards compatible server (supports both protocols) - npx tsx src/examples/server/sseAndStreamableHttpCompatibleServer.ts - ``` - -2. Then run the backwards compatible client: - ```bash - npx tsx src/examples/client/streamableHttpWithSseFallbackClient.ts - ``` - -This demonstrates how the MCP ecosystem ensures interoperability between clients and servers regardless of which protocol version they were built for. diff --git a/typescript-sdk/src/examples/client/multipleClientsParallel.ts b/typescript-sdk/src/examples/client/multipleClientsParallel.ts deleted file mode 100644 index 492235c..0000000 --- a/typescript-sdk/src/examples/client/multipleClientsParallel.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { CallToolRequest, CallToolResultSchema, LoggingMessageNotificationSchema, CallToolResult } from '../../types.js'; - -/** - * Multiple Clients MCP Example - * - * This client demonstrates how to: - * 1. Create multiple MCP clients in parallel - * 2. Each client calls a single tool - * 3. Track notifications from each client independently - */ - -// Command line args processing -const args = process.argv.slice(2); -const serverUrl = args[0] || 'http://localhost:3000/mcp'; - -interface ClientConfig { - id: string; - name: string; - toolName: string; - toolArguments: Record; -} - -async function createAndRunClient(config: ClientConfig): Promise<{ id: string; result: CallToolResult }> { - console.log(`[${config.id}] Creating client: ${config.name}`); - - const client = new Client({ - name: config.name, - version: '1.0.0' - }); - - const transport = new StreamableHTTPClientTransport(new URL(serverUrl)); - - // Set up client-specific error handler - client.onerror = error => { - console.error(`[${config.id}] Client error:`, error); - }; - - // Set up client-specific notification handler - client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - console.log(`[${config.id}] Notification: ${notification.params.data}`); - }); - - try { - // Connect to the server - await client.connect(transport); - console.log(`[${config.id}] Connected to MCP server`); - - // Call the specified tool - console.log(`[${config.id}] Calling tool: ${config.toolName}`); - const toolRequest: CallToolRequest = { - method: 'tools/call', - params: { - name: config.toolName, - arguments: { - ...config.toolArguments, - // Add client ID to arguments for identification in notifications - caller: config.id - } - } - }; - - const result = await client.request(toolRequest, CallToolResultSchema); - console.log(`[${config.id}] Tool call completed`); - - // Keep the connection open for a bit to receive notifications - await new Promise(resolve => setTimeout(resolve, 5000)); - - // Disconnect - await transport.close(); - console.log(`[${config.id}] Disconnected from MCP server`); - - return { id: config.id, result }; - } catch (error) { - console.error(`[${config.id}] Error:`, error); - throw error; - } -} - -async function main(): Promise { - console.log('MCP Multiple Clients Example'); - console.log('============================'); - console.log(`Server URL: ${serverUrl}`); - console.log(''); - - try { - // Define client configurations - const clientConfigs: ClientConfig[] = [ - { - id: 'client1', - name: 'basic-client-1', - toolName: 'start-notification-stream', - toolArguments: { - interval: 3, // 1 second between notifications - count: 5 // Send 5 notifications - } - }, - { - id: 'client2', - name: 'basic-client-2', - toolName: 'start-notification-stream', - toolArguments: { - interval: 2, // 2 seconds between notifications - count: 3 // Send 3 notifications - } - }, - { - id: 'client3', - name: 'basic-client-3', - toolName: 'start-notification-stream', - toolArguments: { - interval: 1, // 0.5 second between notifications - count: 8 // Send 8 notifications - } - } - ]; - - // Start all clients in parallel - console.log(`Starting ${clientConfigs.length} clients in parallel...`); - console.log(''); - - const clientPromises = clientConfigs.map(config => createAndRunClient(config)); - const results = await Promise.all(clientPromises); - - // Display results from all clients - console.log('\n=== Final Results ==='); - results.forEach(({ id, result }) => { - console.log(`\n[${id}] Tool result:`); - if (Array.isArray(result.content)) { - result.content.forEach((item: { type: string; text?: string }) => { - if (item.type === 'text' && item.text) { - console.log(` ${item.text}`); - } else { - console.log(` ${item.type} content:`, item); - } - }); - } else { - console.log(` Unexpected result format:`, result); - } - }); - - console.log('\n=== All clients completed successfully ==='); - } catch (error) { - console.error('Error running multiple clients:', error); - process.exit(1); - } -} - -// Start the example -main().catch((error: unknown) => { - console.error('Error running MCP multiple clients example:', error); - process.exit(1); -}); diff --git a/typescript-sdk/src/examples/client/parallelToolCallsClient.ts b/typescript-sdk/src/examples/client/parallelToolCallsClient.ts deleted file mode 100644 index 2ad249d..0000000 --- a/typescript-sdk/src/examples/client/parallelToolCallsClient.ts +++ /dev/null @@ -1,196 +0,0 @@ -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { - ListToolsRequest, - ListToolsResultSchema, - CallToolResultSchema, - LoggingMessageNotificationSchema, - CallToolResult -} from '../../types.js'; - -/** - * Parallel Tool Calls MCP Client - * - * This client demonstrates how to: - * 1. Start multiple tool calls in parallel - * 2. Track notifications from each tool call using a caller parameter - */ - -// Command line args processing -const args = process.argv.slice(2); -const serverUrl = args[0] || 'http://localhost:3000/mcp'; - -async function main(): Promise { - console.log('MCP Parallel Tool Calls Client'); - console.log('=============================='); - console.log(`Connecting to server at: ${serverUrl}`); - - let client: Client; - let transport: StreamableHTTPClientTransport; - - try { - // Create client with streamable HTTP transport - client = new Client({ - name: 'parallel-tool-calls-client', - version: '1.0.0' - }); - - client.onerror = error => { - console.error('Client error:', error); - }; - - // Connect to the server - transport = new StreamableHTTPClientTransport(new URL(serverUrl)); - await client.connect(transport); - console.log('Successfully connected to MCP server'); - - // Set up notification handler with caller identification - client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - console.log(`Notification: ${notification.params.data}`); - }); - - console.log('List tools'); - const toolsRequest = await listTools(client); - console.log('Tools: ', toolsRequest); - - // 2. Start multiple notification tools in parallel - console.log('\n=== Starting Multiple Notification Streams in Parallel ==='); - const toolResults = await startParallelNotificationTools(client); - - // Log the results from each tool call - for (const [caller, result] of Object.entries(toolResults)) { - console.log(`\n=== Tool result for ${caller} ===`); - result.content.forEach((item: { type: string; text?: string }) => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } else { - console.log(` ${item.type} content:`, item); - } - }); - } - - // 3. Wait for all notifications (10 seconds) - console.log('\n=== Waiting for all notifications ==='); - await new Promise(resolve => setTimeout(resolve, 10000)); - - // 4. Disconnect - console.log('\n=== Disconnecting ==='); - await transport.close(); - console.log('Disconnected from MCP server'); - } catch (error) { - console.error('Error running client:', error); - process.exit(1); - } -} - -/** - * List available tools on the server - */ -async function listTools(client: Client): Promise { - try { - const toolsRequest: ListToolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); - - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } else { - for (const tool of toolsResult.tools) { - console.log(` - ${tool.name}: ${tool.description}`); - } - } - } catch (error) { - console.log(`Tools not supported by this server: ${error}`); - } -} - -/** - * Start multiple notification tools in parallel with different configurations - * Each tool call includes a caller parameter to identify its notifications - */ -async function startParallelNotificationTools(client: Client): Promise> { - try { - // Define multiple tool calls with different configurations - const toolCalls = [ - { - caller: 'fast-notifier', - request: { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 2, // 0.5 second between notifications - count: 10, // Send 10 notifications - caller: 'fast-notifier' // Identify this tool call - } - } - } - }, - { - caller: 'slow-notifier', - request: { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 5, // 2 seconds between notifications - count: 5, // Send 5 notifications - caller: 'slow-notifier' // Identify this tool call - } - } - } - }, - { - caller: 'burst-notifier', - request: { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 1, // 0.1 second between notifications - count: 3, // Send just 3 notifications - caller: 'burst-notifier' // Identify this tool call - } - } - } - } - ]; - - console.log(`Starting ${toolCalls.length} notification tools in parallel...`); - - // Start all tool calls in parallel - const toolPromises = toolCalls.map(({ caller, request }) => { - console.log(`Starting tool call for ${caller}...`); - return client - .request(request, CallToolResultSchema) - .then(result => ({ caller, result })) - .catch(error => { - console.error(`Error in tool call for ${caller}:`, error); - throw error; - }); - }); - - // Wait for all tool calls to complete - const results = await Promise.all(toolPromises); - - // Organize results by caller - const resultsByTool: Record = {}; - results.forEach(({ caller, result }) => { - resultsByTool[caller] = result; - }); - - return resultsByTool; - } catch (error) { - console.error(`Error starting parallel notification tools:`, error); - throw error; - } -} - -// Start the client -main().catch((error: unknown) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); diff --git a/typescript-sdk/src/examples/client/simpleOAuthClient.ts b/typescript-sdk/src/examples/client/simpleOAuthClient.ts deleted file mode 100644 index 3548860..0000000 --- a/typescript-sdk/src/examples/client/simpleOAuthClient.ts +++ /dev/null @@ -1,420 +0,0 @@ -#!/usr/bin/env node - -import { createServer } from 'node:http'; -import { createInterface } from 'node:readline'; -import { URL } from 'node:url'; -import { exec } from 'node:child_process'; -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { OAuthClientInformation, OAuthClientInformationFull, OAuthClientMetadata, OAuthTokens } from '../../shared/auth.js'; -import { CallToolRequest, ListToolsRequest, CallToolResultSchema, ListToolsResultSchema } from '../../types.js'; -import { OAuthClientProvider, UnauthorizedError } from '../../client/auth.js'; - -// Configuration -const DEFAULT_SERVER_URL = 'http://localhost:3000/mcp'; -const CALLBACK_PORT = 8090; // Use different port than auth server (3001) -const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`; - -/** - * In-memory OAuth client provider for demonstration purposes - * In production, you should persist tokens securely - */ -class InMemoryOAuthClientProvider implements OAuthClientProvider { - private _clientInformation?: OAuthClientInformationFull; - private _tokens?: OAuthTokens; - private _codeVerifier?: string; - - constructor( - private readonly _redirectUrl: string | URL, - private readonly _clientMetadata: OAuthClientMetadata, - onRedirect?: (url: URL) => void - ) { - this._onRedirect = - onRedirect || - (url => { - console.log(`Redirect to: ${url.toString()}`); - }); - } - - private _onRedirect: (url: URL) => void; - - get redirectUrl(): string | URL { - return this._redirectUrl; - } - - get clientMetadata(): OAuthClientMetadata { - return this._clientMetadata; - } - - clientInformation(): OAuthClientInformation | undefined { - return this._clientInformation; - } - - saveClientInformation(clientInformation: OAuthClientInformationFull): void { - this._clientInformation = clientInformation; - } - - tokens(): OAuthTokens | undefined { - return this._tokens; - } - - saveTokens(tokens: OAuthTokens): void { - this._tokens = tokens; - } - - redirectToAuthorization(authorizationUrl: URL): void { - this._onRedirect(authorizationUrl); - } - - saveCodeVerifier(codeVerifier: string): void { - this._codeVerifier = codeVerifier; - } - - codeVerifier(): string { - if (!this._codeVerifier) { - throw new Error('No code verifier saved'); - } - return this._codeVerifier; - } -} -/** - * Interactive MCP client with OAuth authentication - * Demonstrates the complete OAuth flow with browser-based authorization - */ -class InteractiveOAuthClient { - private client: Client | null = null; - private readonly rl = createInterface({ - input: process.stdin, - output: process.stdout - }); - - constructor(private serverUrl: string) {} - - /** - * Prompts user for input via readline - */ - private async question(query: string): Promise { - return new Promise(resolve => { - this.rl.question(query, resolve); - }); - } - - /** - * Opens the authorization URL in the user's default browser - */ - private async openBrowser(url: string): Promise { - console.log(`🌐 Opening browser for authorization: ${url}`); - - const command = `open "${url}"`; - - exec(command, error => { - if (error) { - console.error(`Failed to open browser: ${error.message}`); - console.log(`Please manually open: ${url}`); - } - }); - } - /** - * Example OAuth callback handler - in production, use a more robust approach - * for handling callbacks and storing tokens - */ - /** - * Starts a temporary HTTP server to receive the OAuth callback - */ - private async waitForOAuthCallback(): Promise { - return new Promise((resolve, reject) => { - const server = createServer((req, res) => { - // Ignore favicon requests - if (req.url === '/favicon.ico') { - res.writeHead(404); - res.end(); - return; - } - - console.log(`📥 Received callback: ${req.url}`); - const parsedUrl = new URL(req.url || '', 'http://localhost'); - const code = parsedUrl.searchParams.get('code'); - const error = parsedUrl.searchParams.get('error'); - - if (code) { - console.log(`✅ Authorization code received: ${code?.substring(0, 10)}...`); - res.writeHead(200, { 'Content-Type': 'text/html' }); - res.end(` - - -

Authorization Successful!

-

You can close this window and return to the terminal.

- - - - `); - - resolve(code); - setTimeout(() => server.close(), 3000); - } else if (error) { - console.log(`❌ Authorization error: ${error}`); - res.writeHead(400, { 'Content-Type': 'text/html' }); - res.end(` - - -

Authorization Failed

-

Error: ${error}

- - - `); - reject(new Error(`OAuth authorization failed: ${error}`)); - } else { - console.log(`❌ No authorization code or error in callback`); - res.writeHead(400); - res.end('Bad request'); - reject(new Error('No authorization code provided')); - } - }); - - server.listen(CALLBACK_PORT, () => { - console.log(`OAuth callback server started on http://localhost:${CALLBACK_PORT}`); - }); - }); - } - - private async attemptConnection(oauthProvider: InMemoryOAuthClientProvider): Promise { - console.log('🚢 Creating transport with OAuth provider...'); - const baseUrl = new URL(this.serverUrl); - const transport = new StreamableHTTPClientTransport(baseUrl, { - authProvider: oauthProvider - }); - console.log('🚢 Transport created'); - - try { - console.log('🔌 Attempting connection (this will trigger OAuth redirect)...'); - await this.client!.connect(transport); - console.log('✅ Connected successfully'); - } catch (error) { - if (error instanceof UnauthorizedError) { - console.log('🔐 OAuth required - waiting for authorization...'); - const callbackPromise = this.waitForOAuthCallback(); - const authCode = await callbackPromise; - await transport.finishAuth(authCode); - console.log('🔐 Authorization code received:', authCode); - console.log('🔌 Reconnecting with authenticated transport...'); - await this.attemptConnection(oauthProvider); - } else { - console.error('❌ Connection failed with non-auth error:', error); - throw error; - } - } - } - - /** - * Establishes connection to the MCP server with OAuth authentication - */ - async connect(): Promise { - console.log(`🔗 Attempting to connect to ${this.serverUrl}...`); - - const clientMetadata: OAuthClientMetadata = { - client_name: 'Simple OAuth MCP Client', - redirect_uris: [CALLBACK_URL], - grant_types: ['authorization_code', 'refresh_token'], - response_types: ['code'], - token_endpoint_auth_method: 'client_secret_post', - scope: 'mcp:tools' - }; - - console.log('🔐 Creating OAuth provider...'); - const oauthProvider = new InMemoryOAuthClientProvider(CALLBACK_URL, clientMetadata, (redirectUrl: URL) => { - console.log(`📌 OAuth redirect handler called - opening browser`); - console.log(`Opening browser to: ${redirectUrl.toString()}`); - this.openBrowser(redirectUrl.toString()); - }); - console.log('🔐 OAuth provider created'); - - console.log('👤 Creating MCP client...'); - this.client = new Client( - { - name: 'simple-oauth-client', - version: '1.0.0' - }, - { capabilities: {} } - ); - console.log('👤 Client created'); - - console.log('🔐 Starting OAuth flow...'); - - await this.attemptConnection(oauthProvider); - - // Start interactive loop - await this.interactiveLoop(); - } - - /** - * Main interactive loop for user commands - */ - async interactiveLoop(): Promise { - console.log('\n🎯 Interactive MCP Client with OAuth'); - console.log('Commands:'); - console.log(' list - List available tools'); - console.log(' call [args] - Call a tool'); - console.log(' quit - Exit the client'); - console.log(); - - while (true) { - try { - const command = await this.question('mcp> '); - - if (!command.trim()) { - continue; - } - - if (command === 'quit') { - console.log('\n👋 Goodbye!'); - this.close(); - process.exit(0); - } else if (command === 'list') { - await this.listTools(); - } else if (command.startsWith('call ')) { - await this.handleCallTool(command); - } else { - console.log("❌ Unknown command. Try 'list', 'call ', or 'quit'"); - } - } catch (error) { - if (error instanceof Error && error.message === 'SIGINT') { - console.log('\n\n👋 Goodbye!'); - break; - } - console.error('❌ Error:', error); - } - } - } - - private async listTools(): Promise { - if (!this.client) { - console.log('❌ Not connected to server'); - return; - } - - try { - const request: ListToolsRequest = { - method: 'tools/list', - params: {} - }; - - const result = await this.client.request(request, ListToolsResultSchema); - - if (result.tools && result.tools.length > 0) { - console.log('\n📋 Available tools:'); - result.tools.forEach((tool, index) => { - console.log(`${index + 1}. ${tool.name}`); - if (tool.description) { - console.log(` Description: ${tool.description}`); - } - console.log(); - }); - } else { - console.log('No tools available'); - } - } catch (error) { - console.error('❌ Failed to list tools:', error); - } - } - - private async handleCallTool(command: string): Promise { - const parts = command.split(/\s+/); - const toolName = parts[1]; - - if (!toolName) { - console.log('❌ Please specify a tool name'); - return; - } - - // Parse arguments (simple JSON-like format) - let toolArgs: Record = {}; - if (parts.length > 2) { - const argsString = parts.slice(2).join(' '); - try { - toolArgs = JSON.parse(argsString); - } catch { - console.log('❌ Invalid arguments format (expected JSON)'); - return; - } - } - - await this.callTool(toolName, toolArgs); - } - - private async callTool(toolName: string, toolArgs: Record): Promise { - if (!this.client) { - console.log('❌ Not connected to server'); - return; - } - - try { - const request: CallToolRequest = { - method: 'tools/call', - params: { - name: toolName, - arguments: toolArgs - } - }; - - const result = await this.client.request(request, CallToolResultSchema); - - console.log(`\n🔧 Tool '${toolName}' result:`); - if (result.content) { - result.content.forEach(content => { - if (content.type === 'text') { - console.log(content.text); - } else { - console.log(content); - } - }); - } else { - console.log(result); - } - } catch (error) { - console.error(`❌ Failed to call tool '${toolName}':`, error); - } - } - - close(): void { - this.rl.close(); - if (this.client) { - // Note: Client doesn't have a close method in the current implementation - // This would typically close the transport connection - } - } -} - -/** - * Main entry point - */ -async function main(): Promise { - const serverUrl = process.env.MCP_SERVER_URL || DEFAULT_SERVER_URL; - - console.log('🚀 Simple MCP OAuth Client'); - console.log(`Connecting to: ${serverUrl}`); - console.log(); - - const client = new InteractiveOAuthClient(serverUrl); - - // Handle graceful shutdown - process.on('SIGINT', () => { - console.log('\n\n👋 Goodbye!'); - client.close(); - process.exit(0); - }); - - try { - await client.connect(); - } catch (error) { - console.error('Failed to start client:', error); - process.exit(1); - } finally { - client.close(); - } -} - -// Run if this file is executed directly -main().catch(error => { - console.error('Unhandled error:', error); - process.exit(1); -}); diff --git a/typescript-sdk/src/examples/client/simpleStreamableHttp.ts b/typescript-sdk/src/examples/client/simpleStreamableHttp.ts deleted file mode 100644 index bf58a7a..0000000 --- a/typescript-sdk/src/examples/client/simpleStreamableHttp.ts +++ /dev/null @@ -1,837 +0,0 @@ -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { createInterface } from 'node:readline'; -import { - ListToolsRequest, - ListToolsResultSchema, - CallToolRequest, - CallToolResultSchema, - ListPromptsRequest, - ListPromptsResultSchema, - GetPromptRequest, - GetPromptResultSchema, - ListResourcesRequest, - ListResourcesResultSchema, - LoggingMessageNotificationSchema, - ResourceListChangedNotificationSchema, - ElicitRequestSchema, - ResourceLink, - ReadResourceRequest, - ReadResourceResultSchema -} from '../../types.js'; -import { getDisplayName } from '../../shared/metadataUtils.js'; -import { Ajv } from 'ajv'; - -// Create readline interface for user input -const readline = createInterface({ - input: process.stdin, - output: process.stdout -}); - -// Track received notifications for debugging resumability -let notificationCount = 0; - -// Global client and transport for interactive commands -let client: Client | null = null; -let transport: StreamableHTTPClientTransport | null = null; -let serverUrl = 'http://localhost:3000/mcp'; -let notificationsToolLastEventId: string | undefined = undefined; -let sessionId: string | undefined = undefined; - -async function main(): Promise { - console.log('MCP Interactive Client'); - console.log('====================='); - - // Connect to server immediately with default settings - await connect(); - - // Print help and start the command loop - printHelp(); - commandLoop(); -} - -function printHelp(): void { - console.log('\nAvailable commands:'); - console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); - console.log(' disconnect - Disconnect from server'); - console.log(' terminate-session - Terminate the current session'); - console.log(' reconnect - Reconnect to the server'); - console.log(' list-tools - List available tools'); - console.log(' call-tool [args] - Call a tool with optional JSON arguments'); - console.log(' greet [name] - Call the greet tool'); - console.log(' multi-greet [name] - Call the multi-greet tool with notifications'); - console.log(' collect-info [type] - Test elicitation with collect-user-info tool (contact/preferences/feedback)'); - console.log(' start-notifications [interval] [count] - Start periodic notifications'); - console.log(' run-notifications-tool-with-resumability [interval] [count] - Run notification tool with resumability'); - console.log(' list-prompts - List available prompts'); - console.log(' get-prompt [name] [args] - Get a prompt with optional JSON arguments'); - console.log(' list-resources - List available resources'); - console.log(' read-resource - Read a specific resource by URI'); - console.log(' help - Show this help'); - console.log(' quit - Exit the program'); -} - -function commandLoop(): void { - readline.question('\n> ', async input => { - const args = input.trim().split(/\s+/); - const command = args[0]?.toLowerCase(); - - try { - switch (command) { - case 'connect': - await connect(args[1]); - break; - - case 'disconnect': - await disconnect(); - break; - - case 'terminate-session': - await terminateSession(); - break; - - case 'reconnect': - await reconnect(); - break; - - case 'list-tools': - await listTools(); - break; - - case 'call-tool': - if (args.length < 2) { - console.log('Usage: call-tool [args]'); - } else { - const toolName = args[1]; - let toolArgs = {}; - if (args.length > 2) { - try { - toolArgs = JSON.parse(args.slice(2).join(' ')); - } catch { - console.log('Invalid JSON arguments. Using empty args.'); - } - } - await callTool(toolName, toolArgs); - } - break; - - case 'greet': - await callGreetTool(args[1] || 'MCP User'); - break; - - case 'multi-greet': - await callMultiGreetTool(args[1] || 'MCP User'); - break; - - case 'collect-info': - await callCollectInfoTool(args[1] || 'contact'); - break; - - case 'start-notifications': { - const interval = args[1] ? parseInt(args[1], 10) : 2000; - const count = args[2] ? parseInt(args[2], 10) : 10; - await startNotifications(interval, count); - break; - } - - case 'run-notifications-tool-with-resumability': { - const interval = args[1] ? parseInt(args[1], 10) : 2000; - const count = args[2] ? parseInt(args[2], 10) : 10; - await runNotificationsToolWithResumability(interval, count); - break; - } - - case 'list-prompts': - await listPrompts(); - break; - - case 'get-prompt': - if (args.length < 2) { - console.log('Usage: get-prompt [args]'); - } else { - const promptName = args[1]; - let promptArgs = {}; - if (args.length > 2) { - try { - promptArgs = JSON.parse(args.slice(2).join(' ')); - } catch { - console.log('Invalid JSON arguments. Using empty args.'); - } - } - await getPrompt(promptName, promptArgs); - } - break; - - case 'list-resources': - await listResources(); - break; - - case 'read-resource': - if (args.length < 2) { - console.log('Usage: read-resource '); - } else { - await readResource(args[1]); - } - break; - - case 'help': - printHelp(); - break; - - case 'quit': - case 'exit': - await cleanup(); - return; - - default: - if (command) { - console.log(`Unknown command: ${command}`); - } - break; - } - } catch (error) { - console.error(`Error executing command: ${error}`); - } - - // Continue the command loop - commandLoop(); - }); -} - -async function connect(url?: string): Promise { - if (client) { - console.log('Already connected. Disconnect first.'); - return; - } - - if (url) { - serverUrl = url; - } - - console.log(`Connecting to ${serverUrl}...`); - - try { - // Create a new client with elicitation capability - client = new Client( - { - name: 'example-client', - version: '1.0.0' - }, - { - capabilities: { - elicitation: {} - } - } - ); - client.onerror = error => { - console.error('\x1b[31mClient error:', error, '\x1b[0m'); - }; - - // Set up elicitation request handler with proper validation - client.setRequestHandler(ElicitRequestSchema, async request => { - console.log('\n🔔 Elicitation Request Received:'); - console.log(`Message: ${request.params.message}`); - console.log('Requested Schema:'); - console.log(JSON.stringify(request.params.requestedSchema, null, 2)); - - const schema = request.params.requestedSchema; - const properties = schema.properties; - const required = schema.required || []; - - // Set up AJV validator for the requested schema - const ajv = new Ajv(); - const validate = ajv.compile(schema); - - let attempts = 0; - const maxAttempts = 3; - - while (attempts < maxAttempts) { - attempts++; - console.log(`\nPlease provide the following information (attempt ${attempts}/${maxAttempts}):`); - - const content: Record = {}; - let inputCancelled = false; - - // Collect input for each field - for (const [fieldName, fieldSchema] of Object.entries(properties)) { - const field = fieldSchema as { - type?: string; - title?: string; - description?: string; - default?: unknown; - enum?: string[]; - minimum?: number; - maximum?: number; - minLength?: number; - maxLength?: number; - format?: string; - }; - - const isRequired = required.includes(fieldName); - let prompt = `${field.title || fieldName}`; - - // Add helpful information to the prompt - if (field.description) { - prompt += ` (${field.description})`; - } - if (field.enum) { - prompt += ` [options: ${field.enum.join(', ')}]`; - } - if (field.type === 'number' || field.type === 'integer') { - if (field.minimum !== undefined && field.maximum !== undefined) { - prompt += ` [${field.minimum}-${field.maximum}]`; - } else if (field.minimum !== undefined) { - prompt += ` [min: ${field.minimum}]`; - } else if (field.maximum !== undefined) { - prompt += ` [max: ${field.maximum}]`; - } - } - if (field.type === 'string' && field.format) { - prompt += ` [format: ${field.format}]`; - } - if (isRequired) { - prompt += ' *required*'; - } - if (field.default !== undefined) { - prompt += ` [default: ${field.default}]`; - } - - prompt += ': '; - - const answer = await new Promise(resolve => { - readline.question(prompt, input => { - resolve(input.trim()); - }); - }); - - // Check for cancellation - if (answer.toLowerCase() === 'cancel' || answer.toLowerCase() === 'c') { - inputCancelled = true; - break; - } - - // Parse and validate the input - try { - if (answer === '' && field.default !== undefined) { - content[fieldName] = field.default; - } else if (answer === '' && !isRequired) { - // Skip optional empty fields - continue; - } else if (answer === '') { - throw new Error(`${fieldName} is required`); - } else { - // Parse the value based on type - let parsedValue: unknown; - - if (field.type === 'boolean') { - parsedValue = answer.toLowerCase() === 'true' || answer.toLowerCase() === 'yes' || answer === '1'; - } else if (field.type === 'number') { - parsedValue = parseFloat(answer); - if (isNaN(parsedValue as number)) { - throw new Error(`${fieldName} must be a valid number`); - } - } else if (field.type === 'integer') { - parsedValue = parseInt(answer, 10); - if (isNaN(parsedValue as number)) { - throw new Error(`${fieldName} must be a valid integer`); - } - } else if (field.enum) { - if (!field.enum.includes(answer)) { - throw new Error(`${fieldName} must be one of: ${field.enum.join(', ')}`); - } - parsedValue = answer; - } else { - parsedValue = answer; - } - - content[fieldName] = parsedValue; - } - } catch (error) { - console.log(`❌ Error: ${error}`); - // Continue to next attempt - break; - } - } - - if (inputCancelled) { - return { action: 'cancel' }; - } - - // If we didn't complete all fields due to an error, try again - if ( - Object.keys(content).length !== - Object.keys(properties).filter(name => required.includes(name) || content[name] !== undefined).length - ) { - if (attempts < maxAttempts) { - console.log('Please try again...'); - continue; - } else { - console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; - } - } - - // Validate the complete object against the schema - const isValid = validate(content); - - if (!isValid) { - console.log('❌ Validation errors:'); - validate.errors?.forEach(error => { - console.log(` - ${error.instancePath || 'root'}: ${error.message}`); - }); - - if (attempts < maxAttempts) { - console.log('Please correct the errors and try again...'); - continue; - } else { - console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; - } - } - - // Show the collected data and ask for confirmation - console.log('\n✅ Collected data:'); - console.log(JSON.stringify(content, null, 2)); - - const confirmAnswer = await new Promise(resolve => { - readline.question('\nSubmit this information? (yes/no/cancel): ', input => { - resolve(input.trim().toLowerCase()); - }); - }); - - if (confirmAnswer === 'yes' || confirmAnswer === 'y') { - return { - action: 'accept', - content - }; - } else if (confirmAnswer === 'cancel' || confirmAnswer === 'c') { - return { action: 'cancel' }; - } else if (confirmAnswer === 'no' || confirmAnswer === 'n') { - if (attempts < maxAttempts) { - console.log('Please re-enter the information...'); - continue; - } else { - return { action: 'decline' }; - } - } - } - - console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; - }); - - transport = new StreamableHTTPClientTransport(new URL(serverUrl), { - sessionId: sessionId - }); - - // Set up notification handlers - client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - notificationCount++; - console.log(`\nNotification #${notificationCount}: ${notification.params.level} - ${notification.params.data}`); - // Re-display the prompt - process.stdout.write('> '); - }); - - client.setNotificationHandler(ResourceListChangedNotificationSchema, async _ => { - console.log(`\nResource list changed notification received!`); - try { - if (!client) { - console.log('Client disconnected, cannot fetch resources'); - return; - } - const resourcesResult = await client.request( - { - method: 'resources/list', - params: {} - }, - ListResourcesResultSchema - ); - console.log('Available resources count:', resourcesResult.resources.length); - } catch { - console.log('Failed to list resources after change notification'); - } - // Re-display the prompt - process.stdout.write('> '); - }); - - // Connect the client - await client.connect(transport); - sessionId = transport.sessionId; - console.log('Transport created with session ID:', sessionId); - console.log('Connected to MCP server'); - } catch (error) { - console.error('Failed to connect:', error); - client = null; - transport = null; - } -} - -async function disconnect(): Promise { - if (!client || !transport) { - console.log('Not connected.'); - return; - } - - try { - await transport.close(); - console.log('Disconnected from MCP server'); - client = null; - transport = null; - } catch (error) { - console.error('Error disconnecting:', error); - } -} - -async function terminateSession(): Promise { - if (!client || !transport) { - console.log('Not connected.'); - return; - } - - try { - console.log('Terminating session with ID:', transport.sessionId); - await transport.terminateSession(); - console.log('Session terminated successfully'); - - // Check if sessionId was cleared after termination - if (!transport.sessionId) { - console.log('Session ID has been cleared'); - sessionId = undefined; - - // Also close the transport and clear client objects - await transport.close(); - console.log('Transport closed after session termination'); - client = null; - transport = null; - } else { - console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); - console.log('Session ID is still active:', transport.sessionId); - } - } catch (error) { - console.error('Error terminating session:', error); - } -} - -async function reconnect(): Promise { - if (client) { - await disconnect(); - } - await connect(); -} - -async function listTools(): Promise { - if (!client) { - console.log('Not connected to server.'); - return; - } - - try { - const toolsRequest: ListToolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); - - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } else { - for (const tool of toolsResult.tools) { - console.log(` - id: ${tool.name}, name: ${getDisplayName(tool)}, description: ${tool.description}`); - } - } - } catch (error) { - console.log(`Tools not supported by this server (${error})`); - } -} - -async function callTool(name: string, args: Record): Promise { - if (!client) { - console.log('Not connected to server.'); - return; - } - - try { - const request: CallToolRequest = { - method: 'tools/call', - params: { - name, - arguments: args - } - }; - - console.log(`Calling tool '${name}' with args:`, args); - const result = await client.request(request, CallToolResultSchema); - - console.log('Tool result:'); - const resourceLinks: ResourceLink[] = []; - - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } else if (item.type === 'resource_link') { - const resourceLink = item as ResourceLink; - resourceLinks.push(resourceLink); - console.log(` 📁 Resource Link: ${resourceLink.name}`); - console.log(` URI: ${resourceLink.uri}`); - if (resourceLink.mimeType) { - console.log(` Type: ${resourceLink.mimeType}`); - } - if (resourceLink.description) { - console.log(` Description: ${resourceLink.description}`); - } - } else if (item.type === 'resource') { - console.log(` [Embedded Resource: ${item.resource.uri}]`); - } else if (item.type === 'image') { - console.log(` [Image: ${item.mimeType}]`); - } else if (item.type === 'audio') { - console.log(` [Audio: ${item.mimeType}]`); - } else { - console.log(` [Unknown content type]:`, item); - } - }); - - // Offer to read resource links - if (resourceLinks.length > 0) { - console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); - } - } catch (error) { - console.log(`Error calling tool ${name}: ${error}`); - } -} - -async function callGreetTool(name: string): Promise { - await callTool('greet', { name }); -} - -async function callMultiGreetTool(name: string): Promise { - console.log('Calling multi-greet tool with notifications...'); - await callTool('multi-greet', { name }); -} - -async function callCollectInfoTool(infoType: string): Promise { - console.log(`Testing elicitation with collect-user-info tool (${infoType})...`); - await callTool('collect-user-info', { infoType }); -} - -async function startNotifications(interval: number, count: number): Promise { - console.log(`Starting notification stream: interval=${interval}ms, count=${count || 'unlimited'}`); - await callTool('start-notification-stream', { interval, count }); -} - -async function runNotificationsToolWithResumability(interval: number, count: number): Promise { - if (!client) { - console.log('Not connected to server.'); - return; - } - - try { - console.log(`Starting notification stream with resumability: interval=${interval}ms, count=${count || 'unlimited'}`); - console.log(`Using resumption token: ${notificationsToolLastEventId || 'none'}`); - - const request: CallToolRequest = { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { interval, count } - } - }; - - const onLastEventIdUpdate = (event: string) => { - notificationsToolLastEventId = event; - console.log(`Updated resumption token: ${event}`); - }; - - const result = await client.request(request, CallToolResultSchema, { - resumptionToken: notificationsToolLastEventId, - onresumptiontoken: onLastEventIdUpdate - }); - - console.log('Tool result:'); - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } else { - console.log(` ${item.type} content:`, item); - } - }); - } catch (error) { - console.log(`Error starting notification stream: ${error}`); - } -} - -async function listPrompts(): Promise { - if (!client) { - console.log('Not connected to server.'); - return; - } - - try { - const promptsRequest: ListPromptsRequest = { - method: 'prompts/list', - params: {} - }; - const promptsResult = await client.request(promptsRequest, ListPromptsResultSchema); - console.log('Available prompts:'); - if (promptsResult.prompts.length === 0) { - console.log(' No prompts available'); - } else { - for (const prompt of promptsResult.prompts) { - console.log(` - id: ${prompt.name}, name: ${getDisplayName(prompt)}, description: ${prompt.description}`); - } - } - } catch (error) { - console.log(`Prompts not supported by this server (${error})`); - } -} - -async function getPrompt(name: string, args: Record): Promise { - if (!client) { - console.log('Not connected to server.'); - return; - } - - try { - const promptRequest: GetPromptRequest = { - method: 'prompts/get', - params: { - name, - arguments: args as Record - } - }; - - const promptResult = await client.request(promptRequest, GetPromptResultSchema); - console.log('Prompt template:'); - promptResult.messages.forEach((msg, index) => { - console.log(` [${index + 1}] ${msg.role}: ${msg.content.text}`); - }); - } catch (error) { - console.log(`Error getting prompt ${name}: ${error}`); - } -} - -async function listResources(): Promise { - if (!client) { - console.log('Not connected to server.'); - return; - } - - try { - const resourcesRequest: ListResourcesRequest = { - method: 'resources/list', - params: {} - }; - const resourcesResult = await client.request(resourcesRequest, ListResourcesResultSchema); - - console.log('Available resources:'); - if (resourcesResult.resources.length === 0) { - console.log(' No resources available'); - } else { - for (const resource of resourcesResult.resources) { - console.log(` - id: ${resource.name}, name: ${getDisplayName(resource)}, description: ${resource.uri}`); - } - } - } catch (error) { - console.log(`Resources not supported by this server (${error})`); - } -} - -async function readResource(uri: string): Promise { - if (!client) { - console.log('Not connected to server.'); - return; - } - - try { - const request: ReadResourceRequest = { - method: 'resources/read', - params: { uri } - }; - - console.log(`Reading resource: ${uri}`); - const result = await client.request(request, ReadResourceResultSchema); - - console.log('Resource contents:'); - for (const content of result.contents) { - console.log(` URI: ${content.uri}`); - if (content.mimeType) { - console.log(` Type: ${content.mimeType}`); - } - - if ('text' in content && typeof content.text === 'string') { - console.log(' Content:'); - console.log(' ---'); - console.log( - content.text - .split('\n') - .map((line: string) => ' ' + line) - .join('\n') - ); - console.log(' ---'); - } else if ('blob' in content && typeof content.blob === 'string') { - console.log(` [Binary data: ${content.blob.length} bytes]`); - } - } - } catch (error) { - console.log(`Error reading resource ${uri}: ${error}`); - } -} - -async function cleanup(): Promise { - if (client && transport) { - try { - // First try to terminate the session gracefully - if (transport.sessionId) { - try { - console.log('Terminating session before exit...'); - await transport.terminateSession(); - console.log('Session terminated successfully'); - } catch (error) { - console.error('Error terminating session:', error); - } - } - - // Then close the transport - await transport.close(); - } catch (error) { - console.error('Error closing transport:', error); - } - } - - process.stdin.setRawMode(false); - readline.close(); - console.log('\nGoodbye!'); - process.exit(0); -} - -// Set up raw mode for keyboard input to capture Escape key -process.stdin.setRawMode(true); -process.stdin.on('data', async data => { - // Check for Escape key (27) - if (data.length === 1 && data[0] === 27) { - console.log('\nESC key pressed. Disconnecting from server...'); - - // Abort current operation and disconnect from server - if (client && transport) { - await disconnect(); - console.log('Disconnected. Press Enter to continue.'); - } else { - console.log('Not connected to server.'); - } - - // Re-display the prompt - process.stdout.write('> '); - } -}); - -// Handle Ctrl+C -process.on('SIGINT', async () => { - console.log('\nReceived SIGINT. Cleaning up...'); - await cleanup(); -}); - -// Start the interactive client -main().catch((error: unknown) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); diff --git a/typescript-sdk/src/examples/client/streamableHttpWithSseFallbackClient.ts b/typescript-sdk/src/examples/client/streamableHttpWithSseFallbackClient.ts deleted file mode 100644 index 657f489..0000000 --- a/typescript-sdk/src/examples/client/streamableHttpWithSseFallbackClient.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { SSEClientTransport } from '../../client/sse.js'; -import { - ListToolsRequest, - ListToolsResultSchema, - CallToolRequest, - CallToolResultSchema, - LoggingMessageNotificationSchema -} from '../../types.js'; - -/** - * Simplified Backwards Compatible MCP Client - * - * This client demonstrates backward compatibility with both: - * 1. Modern servers using Streamable HTTP transport (protocol version 2025-03-26) - * 2. Older servers using HTTP+SSE transport (protocol version 2024-11-05) - * - * Following the MCP specification for backwards compatibility: - * - Attempts to POST an initialize request to the server URL first (modern transport) - * - If that fails with 4xx status, falls back to GET request for SSE stream (older transport) - */ - -// Command line args processing -const args = process.argv.slice(2); -const serverUrl = args[0] || 'http://localhost:3000/mcp'; - -async function main(): Promise { - console.log('MCP Backwards Compatible Client'); - console.log('==============================='); - console.log(`Connecting to server at: ${serverUrl}`); - - let client: Client; - let transport: StreamableHTTPClientTransport | SSEClientTransport; - - try { - // Try connecting with automatic transport detection - const connection = await connectWithBackwardsCompatibility(serverUrl); - client = connection.client; - transport = connection.transport; - - // Set up notification handler - client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - console.log(`Notification: ${notification.params.level} - ${notification.params.data}`); - }); - - // DEMO WORKFLOW: - // 1. List available tools - console.log('\n=== Listing Available Tools ==='); - await listTools(client); - - // 2. Call the notification tool - console.log('\n=== Starting Notification Stream ==='); - await startNotificationTool(client); - - // 3. Wait for all notifications (5 seconds) - console.log('\n=== Waiting for all notifications ==='); - await new Promise(resolve => setTimeout(resolve, 5000)); - - // 4. Disconnect - console.log('\n=== Disconnecting ==='); - await transport.close(); - console.log('Disconnected from MCP server'); - } catch (error) { - console.error('Error running client:', error); - process.exit(1); - } -} - -/** - * Connect to an MCP server with backwards compatibility - * Following the spec for client backward compatibility - */ -async function connectWithBackwardsCompatibility(url: string): Promise<{ - client: Client; - transport: StreamableHTTPClientTransport | SSEClientTransport; - transportType: 'streamable-http' | 'sse'; -}> { - console.log('1. Trying Streamable HTTP transport first...'); - - // Step 1: Try Streamable HTTP transport first - const client = new Client({ - name: 'backwards-compatible-client', - version: '1.0.0' - }); - - client.onerror = error => { - console.error('Client error:', error); - }; - const baseUrl = new URL(url); - - try { - // Create modern transport - const streamableTransport = new StreamableHTTPClientTransport(baseUrl); - await client.connect(streamableTransport); - - console.log('Successfully connected using modern Streamable HTTP transport.'); - return { - client, - transport: streamableTransport, - transportType: 'streamable-http' - }; - } catch (error) { - // Step 2: If transport fails, try the older SSE transport - console.log(`StreamableHttp transport connection failed: ${error}`); - console.log('2. Falling back to deprecated HTTP+SSE transport...'); - - try { - // Create SSE transport pointing to /sse endpoint - const sseTransport = new SSEClientTransport(baseUrl); - const sseClient = new Client({ - name: 'backwards-compatible-client', - version: '1.0.0' - }); - await sseClient.connect(sseTransport); - - console.log('Successfully connected using deprecated HTTP+SSE transport.'); - return { - client: sseClient, - transport: sseTransport, - transportType: 'sse' - }; - } catch (sseError) { - console.error(`Failed to connect with either transport method:\n1. Streamable HTTP error: ${error}\n2. SSE error: ${sseError}`); - throw new Error('Could not connect to server with any available transport'); - } - } -} - -/** - * List available tools on the server - */ -async function listTools(client: Client): Promise { - try { - const toolsRequest: ListToolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); - - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } else { - for (const tool of toolsResult.tools) { - console.log(` - ${tool.name}: ${tool.description}`); - } - } - } catch (error) { - console.log(`Tools not supported by this server: ${error}`); - } -} - -/** - * Start a notification stream by calling the notification tool - */ -async function startNotificationTool(client: Client): Promise { - try { - // Call the notification tool using reasonable defaults - const request: CallToolRequest = { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 1000, // 1 second between notifications - count: 5 // Send 5 notifications - } - } - }; - - console.log('Calling notification tool...'); - const result = await client.request(request, CallToolResultSchema); - - console.log('Tool result:'); - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } else { - console.log(` ${item.type} content:`, item); - } - }); - } catch (error) { - console.log(`Error calling notification tool: ${error}`); - } -} - -// Start the client -main().catch((error: unknown) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); diff --git a/typescript-sdk/src/examples/server/demoInMemoryOAuthProvider.test.ts b/typescript-sdk/src/examples/server/demoInMemoryOAuthProvider.test.ts deleted file mode 100644 index 0fc7daf..0000000 --- a/typescript-sdk/src/examples/server/demoInMemoryOAuthProvider.test.ts +++ /dev/null @@ -1,285 +0,0 @@ -import { Response } from 'express'; -import { DemoInMemoryAuthProvider, DemoInMemoryClientsStore } from './demoInMemoryOAuthProvider.js'; -import { AuthorizationParams } from '../../server/auth/provider.js'; -import { OAuthClientInformationFull } from '../../shared/auth.js'; -import { InvalidRequestError } from '../../server/auth/errors.js'; - -describe('DemoInMemoryAuthProvider', () => { - let provider: DemoInMemoryAuthProvider; - let mockResponse: Response & { getRedirectUrl: () => string }; - - const createMockResponse = (): Response & { getRedirectUrl: () => string } => { - let capturedRedirectUrl: string | undefined; - - const mockRedirect = jest.fn().mockImplementation((url: string | number, status?: number) => { - if (typeof url === 'string') { - capturedRedirectUrl = url; - } else if (typeof status === 'string') { - capturedRedirectUrl = status; - } - return mockResponse; - }); - - const mockResponse = { - redirect: mockRedirect, - status: jest.fn().mockReturnThis(), - json: jest.fn().mockReturnThis(), - send: jest.fn().mockReturnThis(), - getRedirectUrl: () => { - if (capturedRedirectUrl === undefined) { - throw new Error('No redirect URL was captured. Ensure redirect() was called first.'); - } - return capturedRedirectUrl; - } - } as unknown as Response & { getRedirectUrl: () => string }; - - return mockResponse; - }; - - beforeEach(() => { - provider = new DemoInMemoryAuthProvider(); - mockResponse = createMockResponse(); - }); - - describe('authorize', () => { - const validClient: OAuthClientInformationFull = { - client_id: 'test-client', - client_secret: 'test-secret', - redirect_uris: ['https://example.com/callback', 'https://example.com/callback2'], - scope: 'test-scope' - }; - - it('should redirect to the requested redirect_uri when valid', async () => { - const params: AuthorizationParams = { - redirectUri: 'https://example.com/callback', - state: 'test-state', - codeChallenge: 'test-challenge', - scopes: ['test-scope'] - }; - - await provider.authorize(validClient, params, mockResponse); - - expect(mockResponse.redirect).toHaveBeenCalled(); - expect(mockResponse.getRedirectUrl()).toBeDefined(); - - const url = new URL(mockResponse.getRedirectUrl()); - expect(url.origin + url.pathname).toBe('https://example.com/callback'); - expect(url.searchParams.get('state')).toBe('test-state'); - expect(url.searchParams.has('code')).toBe(true); - }); - - it('should throw InvalidRequestError for unregistered redirect_uri', async () => { - const params: AuthorizationParams = { - redirectUri: 'https://evil.com/callback', - state: 'test-state', - codeChallenge: 'test-challenge', - scopes: ['test-scope'] - }; - - await expect(provider.authorize(validClient, params, mockResponse)).rejects.toThrow(InvalidRequestError); - - await expect(provider.authorize(validClient, params, mockResponse)).rejects.toThrow('Unregistered redirect_uri'); - - expect(mockResponse.redirect).not.toHaveBeenCalled(); - }); - - it('should generate unique authorization codes for multiple requests', async () => { - const params1: AuthorizationParams = { - redirectUri: 'https://example.com/callback', - state: 'state-1', - codeChallenge: 'challenge-1', - scopes: ['test-scope'] - }; - - const params2: AuthorizationParams = { - redirectUri: 'https://example.com/callback', - state: 'state-2', - codeChallenge: 'challenge-2', - scopes: ['test-scope'] - }; - - await provider.authorize(validClient, params1, mockResponse); - const firstRedirectUrl = mockResponse.getRedirectUrl(); - const firstCode = new URL(firstRedirectUrl).searchParams.get('code'); - - // Reset the mock for the second call - mockResponse = createMockResponse(); - await provider.authorize(validClient, params2, mockResponse); - const secondRedirectUrl = mockResponse.getRedirectUrl(); - const secondCode = new URL(secondRedirectUrl).searchParams.get('code'); - - expect(firstCode).toBeDefined(); - expect(secondCode).toBeDefined(); - expect(firstCode).not.toBe(secondCode); - }); - - it('should handle params without state', async () => { - const params: AuthorizationParams = { - redirectUri: 'https://example.com/callback', - codeChallenge: 'test-challenge', - scopes: ['test-scope'] - }; - - await provider.authorize(validClient, params, mockResponse); - - expect(mockResponse.redirect).toHaveBeenCalled(); - expect(mockResponse.getRedirectUrl()).toBeDefined(); - - const url = new URL(mockResponse.getRedirectUrl()); - expect(url.searchParams.has('state')).toBe(false); - expect(url.searchParams.has('code')).toBe(true); - }); - }); - - describe('challengeForAuthorizationCode', () => { - const validClient: OAuthClientInformationFull = { - client_id: 'test-client', - client_secret: 'test-secret', - redirect_uris: ['https://example.com/callback'], - scope: 'test-scope' - }; - - it('should return the code challenge for a valid authorization code', async () => { - const params: AuthorizationParams = { - redirectUri: 'https://example.com/callback', - state: 'test-state', - codeChallenge: 'test-challenge-value', - scopes: ['test-scope'] - }; - - await provider.authorize(validClient, params, mockResponse); - const code = new URL(mockResponse.getRedirectUrl()).searchParams.get('code')!; - - const challenge = await provider.challengeForAuthorizationCode(validClient, code); - expect(challenge).toBe('test-challenge-value'); - }); - - it('should throw error for invalid authorization code', async () => { - await expect(provider.challengeForAuthorizationCode(validClient, 'invalid-code')).rejects.toThrow('Invalid authorization code'); - }); - }); - - describe('exchangeAuthorizationCode', () => { - const validClient: OAuthClientInformationFull = { - client_id: 'test-client', - client_secret: 'test-secret', - redirect_uris: ['https://example.com/callback'], - scope: 'test-scope' - }; - - it('should exchange valid authorization code for tokens', async () => { - const params: AuthorizationParams = { - redirectUri: 'https://example.com/callback', - state: 'test-state', - codeChallenge: 'test-challenge', - scopes: ['test-scope', 'other-scope'] - }; - - await provider.authorize(validClient, params, mockResponse); - const code = new URL(mockResponse.getRedirectUrl()).searchParams.get('code')!; - - const tokens = await provider.exchangeAuthorizationCode(validClient, code); - - expect(tokens).toEqual({ - access_token: expect.any(String), - token_type: 'bearer', - expires_in: 3600, - scope: 'test-scope other-scope' - }); - }); - - it('should throw error for invalid authorization code', async () => { - await expect(provider.exchangeAuthorizationCode(validClient, 'invalid-code')).rejects.toThrow('Invalid authorization code'); - }); - - it('should throw error when client_id does not match', async () => { - const params: AuthorizationParams = { - redirectUri: 'https://example.com/callback', - state: 'test-state', - codeChallenge: 'test-challenge', - scopes: ['test-scope'] - }; - - await provider.authorize(validClient, params, mockResponse); - const code = new URL(mockResponse.getRedirectUrl()).searchParams.get('code')!; - - const differentClient: OAuthClientInformationFull = { - client_id: 'different-client', - client_secret: 'different-secret', - redirect_uris: ['https://example.com/callback'], - scope: 'test-scope' - }; - - await expect(provider.exchangeAuthorizationCode(differentClient, code)).rejects.toThrow( - 'Authorization code was not issued to this client' - ); - }); - - it('should delete authorization code after successful exchange', async () => { - const params: AuthorizationParams = { - redirectUri: 'https://example.com/callback', - state: 'test-state', - codeChallenge: 'test-challenge', - scopes: ['test-scope'] - }; - - await provider.authorize(validClient, params, mockResponse); - const code = new URL(mockResponse.getRedirectUrl()).searchParams.get('code')!; - - // First exchange should succeed - await provider.exchangeAuthorizationCode(validClient, code); - - // Second exchange should fail - await expect(provider.exchangeAuthorizationCode(validClient, code)).rejects.toThrow('Invalid authorization code'); - }); - - it('should validate resource when validateResource is provided', async () => { - const validateResource = jest.fn().mockReturnValue(false); - const strictProvider = new DemoInMemoryAuthProvider(validateResource); - - const params: AuthorizationParams = { - redirectUri: 'https://example.com/callback', - state: 'test-state', - codeChallenge: 'test-challenge', - scopes: ['test-scope'], - resource: new URL('https://invalid-resource.com') - }; - - await strictProvider.authorize(validClient, params, mockResponse); - const code = new URL(mockResponse.getRedirectUrl()).searchParams.get('code')!; - - await expect(strictProvider.exchangeAuthorizationCode(validClient, code)).rejects.toThrow( - 'Invalid resource: https://invalid-resource.com/' - ); - - expect(validateResource).toHaveBeenCalledWith(params.resource); - }); - }); - - describe('DemoInMemoryClientsStore', () => { - let store: DemoInMemoryClientsStore; - - beforeEach(() => { - store = new DemoInMemoryClientsStore(); - }); - - it('should register and retrieve client', async () => { - const client: OAuthClientInformationFull = { - client_id: 'test-client', - client_secret: 'test-secret', - redirect_uris: ['https://example.com/callback'], - scope: 'test-scope' - }; - - await store.registerClient(client); - const retrieved = await store.getClient('test-client'); - - expect(retrieved).toEqual(client); - }); - - it('should return undefined for non-existent client', async () => { - const retrieved = await store.getClient('non-existent'); - expect(retrieved).toBeUndefined(); - }); - }); -}); diff --git a/typescript-sdk/src/examples/server/demoInMemoryOAuthProvider.ts b/typescript-sdk/src/examples/server/demoInMemoryOAuthProvider.ts deleted file mode 100644 index ba1d3a4..0000000 --- a/typescript-sdk/src/examples/server/demoInMemoryOAuthProvider.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { AuthorizationParams, OAuthServerProvider } from '../../server/auth/provider.js'; -import { OAuthRegisteredClientsStore } from '../../server/auth/clients.js'; -import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../shared/auth.js'; -import express, { Request, Response } from 'express'; -import { AuthInfo } from '../../server/auth/types.js'; -import { createOAuthMetadata, mcpAuthRouter } from '../../server/auth/router.js'; -import { resourceUrlFromServerUrl } from '../../shared/auth-utils.js'; -import { InvalidRequestError } from '../../server/auth/errors.js'; - -export class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { - private clients = new Map(); - - async getClient(clientId: string) { - return this.clients.get(clientId); - } - - async registerClient(clientMetadata: OAuthClientInformationFull) { - this.clients.set(clientMetadata.client_id, clientMetadata); - return clientMetadata; - } -} - -/** - * 🚨 DEMO ONLY - NOT FOR PRODUCTION - * - * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, - * for example: - * - Persistent token storage - * - Rate limiting - */ -export class DemoInMemoryAuthProvider implements OAuthServerProvider { - clientsStore = new DemoInMemoryClientsStore(); - private codes = new Map< - string, - { - params: AuthorizationParams; - client: OAuthClientInformationFull; - } - >(); - private tokens = new Map(); - - constructor(private validateResource?: (resource?: URL) => boolean) {} - - async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise { - const code = randomUUID(); - - const searchParams = new URLSearchParams({ - code - }); - if (params.state !== undefined) { - searchParams.set('state', params.state); - } - - this.codes.set(code, { - client, - params - }); - - if (!client.redirect_uris.includes(params.redirectUri)) { - throw new InvalidRequestError('Unregistered redirect_uri'); - } - const targetUrl = new URL(params.redirectUri); - targetUrl.search = searchParams.toString(); - res.redirect(targetUrl.toString()); - } - - async challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise { - // Store the challenge with the code data - const codeData = this.codes.get(authorizationCode); - if (!codeData) { - throw new Error('Invalid authorization code'); - } - - return codeData.params.codeChallenge; - } - - async exchangeAuthorizationCode( - client: OAuthClientInformationFull, - authorizationCode: string, - // Note: code verifier is checked in token.ts by default - // it's unused here for that reason. - _codeVerifier?: string - ): Promise { - const codeData = this.codes.get(authorizationCode); - if (!codeData) { - throw new Error('Invalid authorization code'); - } - - if (codeData.client.client_id !== client.client_id) { - throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); - } - - if (this.validateResource && !this.validateResource(codeData.params.resource)) { - throw new Error(`Invalid resource: ${codeData.params.resource}`); - } - - this.codes.delete(authorizationCode); - const token = randomUUID(); - - const tokenData = { - token, - clientId: client.client_id, - scopes: codeData.params.scopes || [], - expiresAt: Date.now() + 3600000, // 1 hour - resource: codeData.params.resource, - type: 'access' - }; - - this.tokens.set(token, tokenData); - - return { - access_token: token, - token_type: 'bearer', - expires_in: 3600, - scope: (codeData.params.scopes || []).join(' ') - }; - } - - async exchangeRefreshToken( - _client: OAuthClientInformationFull, - _refreshToken: string, - _scopes?: string[], - _resource?: URL - ): Promise { - throw new Error('Not implemented for example demo'); - } - - async verifyAccessToken(token: string): Promise { - const tokenData = this.tokens.get(token); - if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) { - throw new Error('Invalid or expired token'); - } - - return { - token, - clientId: tokenData.clientId, - scopes: tokenData.scopes, - expiresAt: Math.floor(tokenData.expiresAt / 1000), - resource: tokenData.resource - }; - } -} - -export const setupAuthServer = ({ - authServerUrl, - mcpServerUrl, - strictResource -}: { - authServerUrl: URL; - mcpServerUrl: URL; - strictResource: boolean; -}): OAuthMetadata => { - // Create separate auth server app - // NOTE: This is a separate app on a separate port to illustrate - // how to separate an OAuth Authorization Server from a Resource - // server in the SDK. The SDK is not intended to be provide a standalone - // authorization server. - - const validateResource = strictResource - ? (resource?: URL) => { - if (!resource) return false; - const expectedResource = resourceUrlFromServerUrl(mcpServerUrl); - return resource.toString() === expectedResource.toString(); - } - : undefined; - - const provider = new DemoInMemoryAuthProvider(validateResource); - const authApp = express(); - authApp.use(express.json()); - // For introspection requests - authApp.use(express.urlencoded()); - - // Add OAuth routes to the auth server - // NOTE: this will also add a protected resource metadata route, - // but it won't be used, so leave it. - authApp.use( - mcpAuthRouter({ - provider, - issuerUrl: authServerUrl, - scopesSupported: ['mcp:tools'] - }) - ); - - authApp.post('/introspect', async (req: Request, res: Response) => { - try { - const { token } = req.body; - if (!token) { - res.status(400).json({ error: 'Token is required' }); - return; - } - - const tokenInfo = await provider.verifyAccessToken(token); - res.json({ - active: true, - client_id: tokenInfo.clientId, - scope: tokenInfo.scopes.join(' '), - exp: tokenInfo.expiresAt, - aud: tokenInfo.resource - }); - return; - } catch (error) { - res.status(401).json({ - active: false, - error: 'Unauthorized', - error_description: `Invalid token: ${error}` - }); - } - }); - - const auth_port = authServerUrl.port; - // Start the auth server - authApp.listen(auth_port, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`OAuth Authorization Server listening on port ${auth_port}`); - }); - - // Note: we could fetch this from the server, but then we end up - // with some top level async which gets annoying. - const oauthMetadata: OAuthMetadata = createOAuthMetadata({ - provider, - issuerUrl: authServerUrl, - scopesSupported: ['mcp:tools'] - }); - - oauthMetadata.introspection_endpoint = new URL('/introspect', authServerUrl).href; - - return oauthMetadata; -}; diff --git a/typescript-sdk/src/examples/server/elicitationExample.ts b/typescript-sdk/src/examples/server/elicitationExample.ts deleted file mode 100644 index 8b1f81d..0000000 --- a/typescript-sdk/src/examples/server/elicitationExample.ts +++ /dev/null @@ -1,476 +0,0 @@ -// Run with: npx tsx src/examples/server/elicitationExample.ts -// -// This example demonstrates how to use elicitation to collect structured user input -// with JSON Schema validation via a local HTTP server with SSE streaming. -// Elicitation allows servers to request user input through the client interface -// with schema-based validation. - -import { randomUUID } from 'node:crypto'; -import cors from 'cors'; -import express, { type Request, type Response } from 'express'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { isInitializeRequest } from '../../types.js'; - -// Create MCP server - it will automatically use AjvJsonSchemaValidator with sensible defaults -// The validator supports format validation (email, date, etc.) if ajv-formats is installed -const mcpServer = new McpServer( - { - name: 'elicitation-example-server', - version: '1.0.0' - }, - { - capabilities: {} - } -); - -/** - * Example 1: Simple user registration tool - * Collects username, email, and password from the user - */ -mcpServer.registerTool( - 'register_user', - { - description: 'Register a new user account by collecting their information', - inputSchema: {} - }, - async () => { - try { - // Request user information through elicitation - const result = await mcpServer.server.elicitInput({ - message: 'Please provide your registration information:', - requestedSchema: { - type: 'object', - properties: { - username: { - type: 'string', - title: 'Username', - description: 'Your desired username (3-20 characters)', - minLength: 3, - maxLength: 20 - }, - email: { - type: 'string', - title: 'Email', - description: 'Your email address', - format: 'email' - }, - password: { - type: 'string', - title: 'Password', - description: 'Your password (min 8 characters)', - minLength: 8 - }, - newsletter: { - type: 'boolean', - title: 'Newsletter', - description: 'Subscribe to newsletter?', - default: false - } - }, - required: ['username', 'email', 'password'] - } - }); - - // Handle the different possible actions - if (result.action === 'accept' && result.content) { - const { username, email, newsletter } = result.content as { - username: string; - email: string; - password: string; - newsletter?: boolean; - }; - - return { - content: [ - { - type: 'text', - text: `Registration successful!\n\nUsername: ${username}\nEmail: ${email}\nNewsletter: ${newsletter ? 'Yes' : 'No'}` - } - ] - }; - } else if (result.action === 'decline') { - return { - content: [ - { - type: 'text', - text: 'Registration cancelled by user.' - } - ] - }; - } else { - return { - content: [ - { - type: 'text', - text: 'Registration was cancelled.' - } - ] - }; - } - } catch (error) { - return { - content: [ - { - type: 'text', - text: `Registration failed: ${error instanceof Error ? error.message : String(error)}` - } - ], - isError: true - }; - } - } -); - -/** - * Example 2: Multi-step workflow with multiple elicitation requests - * Demonstrates how to collect information in multiple steps - */ -mcpServer.registerTool( - 'create_event', - { - description: 'Create a calendar event by collecting event details', - inputSchema: {} - }, - async () => { - try { - // Step 1: Collect basic event information - const basicInfo = await mcpServer.server.elicitInput({ - message: 'Step 1: Enter basic event information', - requestedSchema: { - type: 'object', - properties: { - title: { - type: 'string', - title: 'Event Title', - description: 'Name of the event', - minLength: 1 - }, - description: { - type: 'string', - title: 'Description', - description: 'Event description (optional)' - } - }, - required: ['title'] - } - }); - - if (basicInfo.action !== 'accept' || !basicInfo.content) { - return { - content: [{ type: 'text', text: 'Event creation cancelled.' }] - }; - } - - // Step 2: Collect date and time - const dateTime = await mcpServer.server.elicitInput({ - message: 'Step 2: Enter date and time', - requestedSchema: { - type: 'object', - properties: { - date: { - type: 'string', - title: 'Date', - description: 'Event date', - format: 'date' - }, - startTime: { - type: 'string', - title: 'Start Time', - description: 'Event start time (HH:MM)', - pattern: '^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$' - }, - duration: { - type: 'integer', - title: 'Duration', - description: 'Duration in minutes', - minimum: 15, - maximum: 480 - } - }, - required: ['date', 'startTime', 'duration'] - } - }); - - if (dateTime.action !== 'accept' || !dateTime.content) { - return { - content: [{ type: 'text', text: 'Event creation cancelled.' }] - }; - } - - // Combine all collected information - const event = { - ...basicInfo.content, - ...dateTime.content - }; - - return { - content: [ - { - type: 'text', - text: `Event created successfully!\n\n${JSON.stringify(event, null, 2)}` - } - ] - }; - } catch (error) { - return { - content: [ - { - type: 'text', - text: `Event creation failed: ${error instanceof Error ? error.message : String(error)}` - } - ], - isError: true - }; - } - } -); - -/** - * Example 3: Collecting address information - * Demonstrates validation with patterns and optional fields - */ -mcpServer.registerTool( - 'update_shipping_address', - { - description: 'Update shipping address with validation', - inputSchema: {} - }, - async () => { - try { - const result = await mcpServer.server.elicitInput({ - message: 'Please provide your shipping address:', - requestedSchema: { - type: 'object', - properties: { - name: { - type: 'string', - title: 'Full Name', - description: 'Recipient name', - minLength: 1 - }, - street: { - type: 'string', - title: 'Street Address', - minLength: 1 - }, - city: { - type: 'string', - title: 'City', - minLength: 1 - }, - state: { - type: 'string', - title: 'State/Province', - minLength: 2, - maxLength: 2 - }, - zipCode: { - type: 'string', - title: 'ZIP/Postal Code', - description: '5-digit ZIP code', - pattern: '^[0-9]{5}$' - }, - phone: { - type: 'string', - title: 'Phone Number (optional)', - description: 'Contact phone number' - } - }, - required: ['name', 'street', 'city', 'state', 'zipCode'] - } - }); - - if (result.action === 'accept' && result.content) { - return { - content: [ - { - type: 'text', - text: `Address updated successfully!\n\n${JSON.stringify(result.content, null, 2)}` - } - ] - }; - } else if (result.action === 'decline') { - return { - content: [{ type: 'text', text: 'Address update cancelled by user.' }] - }; - } else { - return { - content: [{ type: 'text', text: 'Address update was cancelled.' }] - }; - } - } catch (error) { - return { - content: [ - { - type: 'text', - text: `Address update failed: ${error instanceof Error ? error.message : String(error)}` - } - ], - isError: true - }; - } - } -); - -async function main() { - const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000; - - const app = express(); - app.use(express.json()); - - // Allow CORS for all domains, expose the Mcp-Session-Id header - app.use( - cors({ - origin: '*', - exposedHeaders: ['Mcp-Session-Id'] - }) - ); - - // Map to store transports by session ID - const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}; - - // MCP POST endpoint - const mcpPostHandler = async (req: Request, res: Response) => { - const sessionId = req.headers['mcp-session-id'] as string | undefined; - if (sessionId) { - console.log(`Received MCP request for session: ${sessionId}`); - } - - try { - let transport: StreamableHTTPServerTransport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport for this session - transport = transports[sessionId]; - } else if (!sessionId && isInitializeRequest(req.body)) { - // New initialization request - create new transport - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - } - }; - - // Connect the transport to the MCP server BEFORE handling the request - await mcpServer.connect(transport); - - await transport.handleRequest(req, res, req.body); - return; - } else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - - // Handle the request with existing transport - await transport.handleRequest(req, res, req.body); - } catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } - }; - - app.post('/mcp', mcpPostHandler); - - // Handle GET requests for SSE streams - const mcpGetHandler = async (req: Request, res: Response) => { - const sessionId = req.headers['mcp-session-id'] as string | undefined; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - - console.log(`Establishing SSE stream for session ${sessionId}`); - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - }; - - app.get('/mcp', mcpGetHandler); - - // Handle DELETE requests for session termination - const mcpDeleteHandler = async (req: Request, res: Response) => { - const sessionId = req.headers['mcp-session-id'] as string | undefined; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - - console.log(`Received session termination request for session ${sessionId}`); - - try { - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - } catch (error) { - console.error('Error handling session termination:', error); - if (!res.headersSent) { - res.status(500).send('Error processing session termination'); - } - } - }; - - app.delete('/mcp', mcpDeleteHandler); - - // Start listening - app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Elicitation example server is running on http://localhost:${PORT}/mcp`); - console.log('Available tools:'); - console.log(' - register_user: Collect user registration information'); - console.log(' - create_event: Multi-step event creation'); - console.log(' - update_shipping_address: Collect and validate address'); - console.log('\nConnect your MCP client to this server using the HTTP transport.'); - }); - - // Handle server shutdown - process.on('SIGINT', async () => { - console.log('Shutting down server...'); - - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); - }); -} - -main().catch(error => { - console.error('Server error:', error); - process.exit(1); -}); diff --git a/typescript-sdk/src/examples/server/jsonResponseStreamableHttp.ts b/typescript-sdk/src/examples/server/jsonResponseStreamableHttp.ts deleted file mode 100644 index 8b64077..0000000 --- a/typescript-sdk/src/examples/server/jsonResponseStreamableHttp.ts +++ /dev/null @@ -1,186 +0,0 @@ -import express, { Request, Response } from 'express'; -import { randomUUID } from 'node:crypto'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { z } from 'zod'; -import { CallToolResult, isInitializeRequest } from '../../types.js'; -import cors from 'cors'; - -// Create an MCP server with implementation details -const getServer = () => { - const server = new McpServer( - { - name: 'json-response-streamable-http-server', - version: '1.0.0' - }, - { - capabilities: { - logging: {} - } - } - ); - - // Register a simple tool that returns a greeting - server.tool( - 'greet', - 'A simple greeting tool', - { - name: z.string().describe('Name to greet') - }, - async ({ name }): Promise => { - return { - content: [ - { - type: 'text', - text: `Hello, ${name}!` - } - ] - }; - } - ); - - // Register a tool that sends multiple greetings with notifications - server.tool( - 'multi-greet', - 'A tool that sends different greetings with delays between them', - { - name: z.string().describe('Name to greet') - }, - async ({ name }, extra): Promise => { - const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); - - await server.sendLoggingMessage( - { - level: 'debug', - data: `Starting multi-greet for ${name}` - }, - extra.sessionId - ); - - await sleep(1000); // Wait 1 second before first greeting - - await server.sendLoggingMessage( - { - level: 'info', - data: `Sending first greeting to ${name}` - }, - extra.sessionId - ); - - await sleep(1000); // Wait another second before second greeting - - await server.sendLoggingMessage( - { - level: 'info', - data: `Sending second greeting to ${name}` - }, - extra.sessionId - ); - - return { - content: [ - { - type: 'text', - text: `Good morning, ${name}!` - } - ] - }; - } - ); - return server; -}; - -const app = express(); -app.use(express.json()); - -// Configure CORS to expose Mcp-Session-Id header for browser-based clients -app.use( - cors({ - origin: '*', // Allow all origins - adjust as needed for production - exposedHeaders: ['Mcp-Session-Id'] - }) -); - -// Map to store transports by session ID -const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}; - -app.post('/mcp', async (req: Request, res: Response) => { - console.log('Received MCP request:', req.body); - try { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id'] as string | undefined; - let transport: StreamableHTTPServerTransport; - - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } else if (!sessionId && isInitializeRequest(req.body)) { - // New initialization request - use JSON response mode - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - enableJsonResponse: true, // Enable JSON response mode - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - - // Connect the transport to the MCP server BEFORE handling the request - const server = getServer(); - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - return; // Already handled - } else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - - // Handle the request with existing transport - no need to reconnect - await transport.handleRequest(req, res, req.body); - } catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); - -// Handle GET requests for SSE streams according to spec -app.get('/mcp', async (req: Request, res: Response) => { - // Since this is a very simple example, we don't support GET requests for this server - // The spec requires returning 405 Method Not Allowed in this case - res.status(405).set('Allow', 'POST').send('Method Not Allowed'); -}); - -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Streamable HTTP Server listening on port ${PORT}`); -}); - -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - process.exit(0); -}); diff --git a/typescript-sdk/src/examples/server/mcpServerOutputSchema.ts b/typescript-sdk/src/examples/server/mcpServerOutputSchema.ts deleted file mode 100644 index 5d1cab0..0000000 --- a/typescript-sdk/src/examples/server/mcpServerOutputSchema.ts +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env node -/** - * Example MCP server using the high-level McpServer API with outputSchema - * This demonstrates how to easily create tools with structured output - */ - -import { McpServer } from '../../server/mcp.js'; -import { StdioServerTransport } from '../../server/stdio.js'; -import { z } from 'zod'; - -const server = new McpServer({ - name: 'mcp-output-schema-high-level-example', - version: '1.0.0' -}); - -// Define a tool with structured output - Weather data -server.registerTool( - 'get_weather', - { - description: 'Get weather information for a city', - inputSchema: { - city: z.string().describe('City name'), - country: z.string().describe('Country code (e.g., US, UK)') - }, - outputSchema: { - temperature: z.object({ - celsius: z.number(), - fahrenheit: z.number() - }), - conditions: z.enum(['sunny', 'cloudy', 'rainy', 'stormy', 'snowy']), - humidity: z.number().min(0).max(100), - wind: z.object({ - speed_kmh: z.number(), - direction: z.string() - }) - } - }, - async ({ city, country }) => { - // Parameters are available but not used in this example - void city; - void country; - // Simulate weather API call - const temp_c = Math.round((Math.random() * 35 - 5) * 10) / 10; - const conditions = ['sunny', 'cloudy', 'rainy', 'stormy', 'snowy'][Math.floor(Math.random() * 5)]; - - const structuredContent = { - temperature: { - celsius: temp_c, - fahrenheit: Math.round(((temp_c * 9) / 5 + 32) * 10) / 10 - }, - conditions, - humidity: Math.round(Math.random() * 100), - wind: { - speed_kmh: Math.round(Math.random() * 50), - direction: ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.floor(Math.random() * 8)] - } - }; - - return { - content: [ - { - type: 'text', - text: JSON.stringify(structuredContent, null, 2) - } - ], - structuredContent - }; - } -); - -async function main() { - const transport = new StdioServerTransport(); - await server.connect(transport); - console.error('High-level Output Schema Example Server running on stdio'); -} - -main().catch(error => { - console.error('Server error:', error); - process.exit(1); -}); diff --git a/typescript-sdk/src/examples/server/simpleSseServer.ts b/typescript-sdk/src/examples/server/simpleSseServer.ts deleted file mode 100644 index b993343..0000000 --- a/typescript-sdk/src/examples/server/simpleSseServer.ts +++ /dev/null @@ -1,174 +0,0 @@ -import express, { Request, Response } from 'express'; -import { McpServer } from '../../server/mcp.js'; -import { SSEServerTransport } from '../../server/sse.js'; -import { z } from 'zod'; -import { CallToolResult } from '../../types.js'; - -/** - * This example server demonstrates the deprecated HTTP+SSE transport - * (protocol version 2024-11-05). It mainly used for testing backward compatible clients. - * - * The server exposes two endpoints: - * - /mcp: For establishing the SSE stream (GET) - * - /messages: For receiving client messages (POST) - * - */ - -// Create an MCP server instance -const getServer = () => { - const server = new McpServer( - { - name: 'simple-sse-server', - version: '1.0.0' - }, - { capabilities: { logging: {} } } - ); - - server.tool( - 'start-notification-stream', - 'Starts sending periodic notifications', - { - interval: z.number().describe('Interval in milliseconds between notifications').default(1000), - count: z.number().describe('Number of notifications to send').default(10) - }, - async ({ interval, count }, extra): Promise => { - const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - - // Send the initial notification - await server.sendLoggingMessage( - { - level: 'info', - data: `Starting notification stream with ${count} messages every ${interval}ms` - }, - extra.sessionId - ); - - // Send periodic notifications - while (counter < count) { - counter++; - await sleep(interval); - - try { - await server.sendLoggingMessage( - { - level: 'info', - data: `Notification #${counter} at ${new Date().toISOString()}` - }, - extra.sessionId - ); - } catch (error) { - console.error('Error sending notification:', error); - } - } - - return { - content: [ - { - type: 'text', - text: `Completed sending ${count} notifications every ${interval}ms` - } - ] - }; - } - ); - return server; -}; - -const app = express(); -app.use(express.json()); - -// Store transports by session ID -const transports: Record = {}; - -// SSE endpoint for establishing the stream -app.get('/mcp', async (req: Request, res: Response) => { - console.log('Received GET request to /sse (establishing SSE stream)'); - - try { - // Create a new SSE transport for the client - // The endpoint for POST messages is '/messages' - const transport = new SSEServerTransport('/messages', res); - - // Store the transport by session ID - const sessionId = transport.sessionId; - transports[sessionId] = transport; - - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - console.log(`SSE transport closed for session ${sessionId}`); - delete transports[sessionId]; - }; - - // Connect the transport to the MCP server - const server = getServer(); - await server.connect(transport); - - console.log(`Established SSE stream with session ID: ${sessionId}`); - } catch (error) { - console.error('Error establishing SSE stream:', error); - if (!res.headersSent) { - res.status(500).send('Error establishing SSE stream'); - } - } -}); - -// Messages endpoint for receiving client JSON-RPC requests -app.post('/messages', async (req: Request, res: Response) => { - console.log('Received POST request to /messages'); - - // Extract session ID from URL query parameter - // In the SSE protocol, this is added by the client based on the endpoint event - const sessionId = req.query.sessionId as string | undefined; - - if (!sessionId) { - console.error('No session ID provided in request URL'); - res.status(400).send('Missing sessionId parameter'); - return; - } - - const transport = transports[sessionId]; - if (!transport) { - console.error(`No active transport found for session ID: ${sessionId}`); - res.status(404).send('Session not found'); - return; - } - - try { - // Handle the POST message with the transport - await transport.handlePostMessage(req, res, req.body); - } catch (error) { - console.error('Error handling request:', error); - if (!res.headersSent) { - res.status(500).send('Error handling request'); - } - } -}); - -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Simple SSE Server (deprecated protocol version 2024-11-05) listening on port ${PORT}`); -}); - -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); diff --git a/typescript-sdk/src/examples/server/simpleStatelessStreamableHttp.ts b/typescript-sdk/src/examples/server/simpleStatelessStreamableHttp.ts deleted file mode 100644 index f71e5db..0000000 --- a/typescript-sdk/src/examples/server/simpleStatelessStreamableHttp.ts +++ /dev/null @@ -1,180 +0,0 @@ -import express, { Request, Response } from 'express'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { z } from 'zod'; -import { CallToolResult, GetPromptResult, ReadResourceResult } from '../../types.js'; -import cors from 'cors'; - -const getServer = () => { - // Create an MCP server with implementation details - const server = new McpServer( - { - name: 'stateless-streamable-http-server', - version: '1.0.0' - }, - { capabilities: { logging: {} } } - ); - - // Register a simple prompt - server.prompt( - 'greeting-template', - 'A simple greeting prompt template', - { - name: z.string().describe('Name to include in greeting') - }, - async ({ name }): Promise => { - return { - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please greet ${name} in a friendly manner.` - } - } - ] - }; - } - ); - - // Register a tool specifically for testing resumability - server.tool( - 'start-notification-stream', - 'Starts sending periodic notifications for testing resumability', - { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(10) - }, - async ({ interval, count }, extra): Promise => { - const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - - while (count === 0 || counter < count) { - counter++; - try { - await server.sendLoggingMessage( - { - level: 'info', - data: `Periodic notification #${counter} at ${new Date().toISOString()}` - }, - extra.sessionId - ); - } catch (error) { - console.error('Error sending notification:', error); - } - // Wait for the specified interval - await sleep(interval); - } - - return { - content: [ - { - type: 'text', - text: `Started sending periodic notifications every ${interval}ms` - } - ] - }; - } - ); - - // Create a simple resource at a fixed URI - server.resource( - 'greeting-resource', - 'https://example.com/greetings/default', - { mimeType: 'text/plain' }, - async (): Promise => { - return { - contents: [ - { - uri: 'https://example.com/greetings/default', - text: 'Hello, world!' - } - ] - }; - } - ); - return server; -}; - -const app = express(); -app.use(express.json()); - -// Configure CORS to expose Mcp-Session-Id header for browser-based clients -app.use( - cors({ - origin: '*', // Allow all origins - adjust as needed for production - exposedHeaders: ['Mcp-Session-Id'] - }) -); - -app.post('/mcp', async (req: Request, res: Response) => { - const server = getServer(); - try { - const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({ - sessionIdGenerator: undefined - }); - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - res.on('close', () => { - console.log('Request closed'); - transport.close(); - server.close(); - }); - } catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); - -app.get('/mcp', async (req: Request, res: Response) => { - console.log('Received GET MCP request'); - res.writeHead(405).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Method not allowed.' - }, - id: null - }) - ); -}); - -app.delete('/mcp', async (req: Request, res: Response) => { - console.log('Received DELETE MCP request'); - res.writeHead(405).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Method not allowed.' - }, - id: null - }) - ); -}); - -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Stateless Streamable HTTP Server listening on port ${PORT}`); -}); - -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - process.exit(0); -}); diff --git a/typescript-sdk/src/examples/server/simpleStreamableHttp.ts b/typescript-sdk/src/examples/server/simpleStreamableHttp.ts deleted file mode 100644 index 5872cb4..0000000 --- a/typescript-sdk/src/examples/server/simpleStreamableHttp.ts +++ /dev/null @@ -1,698 +0,0 @@ -import express, { Request, Response } from 'express'; -import { randomUUID } from 'node:crypto'; -import { z } from 'zod'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js'; -import { requireBearerAuth } from '../../server/auth/middleware/bearerAuth.js'; -import { - CallToolResult, - GetPromptResult, - isInitializeRequest, - PrimitiveSchemaDefinition, - ReadResourceResult, - ResourceLink -} from '../../types.js'; -import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; -import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; -import { OAuthMetadata } from 'src/shared/auth.js'; -import { checkResourceAllowed } from 'src/shared/auth-utils.js'; - -import cors from 'cors'; - -// Check for OAuth flag -const useOAuth = process.argv.includes('--oauth'); -const strictOAuth = process.argv.includes('--oauth-strict'); - -// Create an MCP server with implementation details -const getServer = () => { - const server = new McpServer( - { - name: 'simple-streamable-http-server', - version: '1.0.0', - icons: [{ src: './mcp.svg', sizes: ['512x512'], mimeType: 'image/svg+xml' }], - websiteUrl: 'https://github.com/modelcontextprotocol/typescript-sdk' - }, - { capabilities: { logging: {} } } - ); - - // Register a simple tool that returns a greeting - server.registerTool( - 'greet', - { - title: 'Greeting Tool', // Display name for UI - description: 'A simple greeting tool', - inputSchema: { - name: z.string().describe('Name to greet') - } - }, - async ({ name }): Promise => { - return { - content: [ - { - type: 'text', - text: `Hello, ${name}!` - } - ] - }; - } - ); - - // Register a tool that sends multiple greetings with notifications (with annotations) - server.tool( - 'multi-greet', - 'A tool that sends different greetings with delays between them', - { - name: z.string().describe('Name to greet') - }, - { - title: 'Multiple Greeting Tool', - readOnlyHint: true, - openWorldHint: false - }, - async ({ name }, extra): Promise => { - const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); - - await server.sendLoggingMessage( - { - level: 'debug', - data: `Starting multi-greet for ${name}` - }, - extra.sessionId - ); - - await sleep(1000); // Wait 1 second before first greeting - - await server.sendLoggingMessage( - { - level: 'info', - data: `Sending first greeting to ${name}` - }, - extra.sessionId - ); - - await sleep(1000); // Wait another second before second greeting - - await server.sendLoggingMessage( - { - level: 'info', - data: `Sending second greeting to ${name}` - }, - extra.sessionId - ); - - return { - content: [ - { - type: 'text', - text: `Good morning, ${name}!` - } - ] - }; - } - ); - // Register a tool that demonstrates elicitation (user input collection) - // This creates a closure that captures the server instance - server.tool( - 'collect-user-info', - 'A tool that collects user information through elicitation', - { - infoType: z.enum(['contact', 'preferences', 'feedback']).describe('Type of information to collect') - }, - async ({ infoType }): Promise => { - let message: string; - let requestedSchema: { - type: 'object'; - properties: Record; - required?: string[]; - }; - - switch (infoType) { - case 'contact': - message = 'Please provide your contact information'; - requestedSchema = { - type: 'object', - properties: { - name: { - type: 'string', - title: 'Full Name', - description: 'Your full name' - }, - email: { - type: 'string', - title: 'Email Address', - description: 'Your email address', - format: 'email' - }, - phone: { - type: 'string', - title: 'Phone Number', - description: 'Your phone number (optional)' - } - }, - required: ['name', 'email'] - }; - break; - case 'preferences': - message = 'Please set your preferences'; - requestedSchema = { - type: 'object', - properties: { - theme: { - type: 'string', - title: 'Theme', - description: 'Choose your preferred theme', - enum: ['light', 'dark', 'auto'], - enumNames: ['Light', 'Dark', 'Auto'] - }, - notifications: { - type: 'boolean', - title: 'Enable Notifications', - description: 'Would you like to receive notifications?', - default: true - }, - frequency: { - type: 'string', - title: 'Notification Frequency', - description: 'How often would you like notifications?', - enum: ['daily', 'weekly', 'monthly'], - enumNames: ['Daily', 'Weekly', 'Monthly'] - } - }, - required: ['theme'] - }; - break; - case 'feedback': - message = 'Please provide your feedback'; - requestedSchema = { - type: 'object', - properties: { - rating: { - type: 'integer', - title: 'Rating', - description: 'Rate your experience (1-5)', - minimum: 1, - maximum: 5 - }, - comments: { - type: 'string', - title: 'Comments', - description: 'Additional comments (optional)', - maxLength: 500 - }, - recommend: { - type: 'boolean', - title: 'Would you recommend this?', - description: 'Would you recommend this to others?' - } - }, - required: ['rating', 'recommend'] - }; - break; - default: - throw new Error(`Unknown info type: ${infoType}`); - } - - try { - // Use the underlying server instance to elicit input from the client - const result = await server.server.elicitInput({ - message, - requestedSchema - }); - - if (result.action === 'accept') { - return { - content: [ - { - type: 'text', - text: `Thank you! Collected ${infoType} information: ${JSON.stringify(result.content, null, 2)}` - } - ] - }; - } else if (result.action === 'decline') { - return { - content: [ - { - type: 'text', - text: `No information was collected. User declined ${infoType} information request.` - } - ] - }; - } else { - return { - content: [ - { - type: 'text', - text: `Information collection was cancelled by the user.` - } - ] - }; - } - } catch (error) { - return { - content: [ - { - type: 'text', - text: `Error collecting ${infoType} information: ${error}` - } - ] - }; - } - } - ); - - // Register a simple prompt with title - server.registerPrompt( - 'greeting-template', - { - title: 'Greeting Template', // Display name for UI - description: 'A simple greeting prompt template', - argsSchema: { - name: z.string().describe('Name to include in greeting') - } - }, - async ({ name }): Promise => { - return { - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please greet ${name} in a friendly manner.` - } - } - ] - }; - } - ); - - // Register a tool specifically for testing resumability - server.tool( - 'start-notification-stream', - 'Starts sending periodic notifications for testing resumability', - { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(50) - }, - async ({ interval, count }, extra): Promise => { - const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - - while (count === 0 || counter < count) { - counter++; - try { - await server.sendLoggingMessage( - { - level: 'info', - data: `Periodic notification #${counter} at ${new Date().toISOString()}` - }, - extra.sessionId - ); - } catch (error) { - console.error('Error sending notification:', error); - } - // Wait for the specified interval - await sleep(interval); - } - - return { - content: [ - { - type: 'text', - text: `Started sending periodic notifications every ${interval}ms` - } - ] - }; - } - ); - - // Create a simple resource at a fixed URI - server.registerResource( - 'greeting-resource', - 'https://example.com/greetings/default', - { - title: 'Default Greeting', // Display name for UI - description: 'A simple greeting resource', - mimeType: 'text/plain' - }, - async (): Promise => { - return { - contents: [ - { - uri: 'https://example.com/greetings/default', - text: 'Hello, world!' - } - ] - }; - } - ); - - // Create additional resources for ResourceLink demonstration - server.registerResource( - 'example-file-1', - 'file:///example/file1.txt', - { - title: 'Example File 1', - description: 'First example file for ResourceLink demonstration', - mimeType: 'text/plain' - }, - async (): Promise => { - return { - contents: [ - { - uri: 'file:///example/file1.txt', - text: 'This is the content of file 1' - } - ] - }; - } - ); - - server.registerResource( - 'example-file-2', - 'file:///example/file2.txt', - { - title: 'Example File 2', - description: 'Second example file for ResourceLink demonstration', - mimeType: 'text/plain' - }, - async (): Promise => { - return { - contents: [ - { - uri: 'file:///example/file2.txt', - text: 'This is the content of file 2' - } - ] - }; - } - ); - - // Register a tool that returns ResourceLinks - server.registerTool( - 'list-files', - { - title: 'List Files with ResourceLinks', - description: 'Returns a list of files as ResourceLinks without embedding their content', - inputSchema: { - includeDescriptions: z.boolean().optional().describe('Whether to include descriptions in the resource links') - } - }, - async ({ includeDescriptions = true }): Promise => { - const resourceLinks: ResourceLink[] = [ - { - type: 'resource_link', - uri: 'https://example.com/greetings/default', - name: 'Default Greeting', - mimeType: 'text/plain', - ...(includeDescriptions && { description: 'A simple greeting resource' }) - }, - { - type: 'resource_link', - uri: 'file:///example/file1.txt', - name: 'Example File 1', - mimeType: 'text/plain', - ...(includeDescriptions && { description: 'First example file for ResourceLink demonstration' }) - }, - { - type: 'resource_link', - uri: 'file:///example/file2.txt', - name: 'Example File 2', - mimeType: 'text/plain', - ...(includeDescriptions && { description: 'Second example file for ResourceLink demonstration' }) - } - ]; - - return { - content: [ - { - type: 'text', - text: 'Here are the available files as resource links:' - }, - ...resourceLinks, - { - type: 'text', - text: '\nYou can read any of these resources using their URI.' - } - ] - }; - } - ); - - return server; -}; - -const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; -const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; - -const app = express(); -app.use(express.json()); - -// Allow CORS all domains, expose the Mcp-Session-Id header -app.use( - cors({ - origin: '*', // Allow all origins - exposedHeaders: ['Mcp-Session-Id'] - }) -); - -// Set up OAuth if enabled -let authMiddleware = null; -if (useOAuth) { - // Create auth middleware for MCP endpoints - const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); - const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); - - const oauthMetadata: OAuthMetadata = setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: strictOAuth }); - - const tokenVerifier = { - verifyAccessToken: async (token: string) => { - const endpoint = oauthMetadata.introspection_endpoint; - - if (!endpoint) { - throw new Error('No token verification endpoint available in metadata'); - } - - const response = await fetch(endpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: new URLSearchParams({ - token: token - }).toString() - }); - - if (!response.ok) { - throw new Error(`Invalid or expired token: ${await response.text()}`); - } - - const data = await response.json(); - - if (strictOAuth) { - if (!data.aud) { - throw new Error(`Resource Indicator (RFC8707) missing`); - } - if (!checkResourceAllowed({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { - throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); - } - } - - // Convert the response to AuthInfo format - return { - token, - clientId: data.client_id, - scopes: data.scope ? data.scope.split(' ') : [], - expiresAt: data.exp - }; - } - }; - // Add metadata routes to the main MCP server - app.use( - mcpAuthMetadataRouter({ - oauthMetadata, - resourceServerUrl: mcpServerUrl, - scopesSupported: ['mcp:tools'], - resourceName: 'MCP Demo Server' - }) - ); - - authMiddleware = requireBearerAuth({ - verifier: tokenVerifier, - requiredScopes: [], - resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl) - }); -} - -// Map to store transports by session ID -const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}; - -// MCP POST endpoint with optional auth -const mcpPostHandler = async (req: Request, res: Response) => { - const sessionId = req.headers['mcp-session-id'] as string | undefined; - if (sessionId) { - console.log(`Received MCP request for session: ${sessionId}`); - } else { - console.log('Request body:', req.body); - } - - if (useOAuth && req.auth) { - console.log('Authenticated user:', req.auth); - } - try { - let transport: StreamableHTTPServerTransport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } else if (!sessionId && isInitializeRequest(req.body)) { - // New initialization request - const eventStore = new InMemoryEventStore(); - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - eventStore, // Enable resumability - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - } - }; - - // Connect the transport to the MCP server BEFORE handling the request - // so responses can flow back through the same transport - const server = getServer(); - await server.connect(transport); - - await transport.handleRequest(req, res, req.body); - return; // Already handled - } else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - - // Handle the request with existing transport - no need to reconnect - // The existing transport is already connected to the server - await transport.handleRequest(req, res, req.body); - } catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}; - -// Set up routes with conditional auth middleware -if (useOAuth && authMiddleware) { - app.post('/mcp', authMiddleware, mcpPostHandler); -} else { - app.post('/mcp', mcpPostHandler); -} - -// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) -const mcpGetHandler = async (req: Request, res: Response) => { - const sessionId = req.headers['mcp-session-id'] as string | undefined; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - - if (useOAuth && req.auth) { - console.log('Authenticated SSE connection from user:', req.auth); - } - - // Check for Last-Event-ID header for resumability - const lastEventId = req.headers['last-event-id'] as string | undefined; - if (lastEventId) { - console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); - } else { - console.log(`Establishing new SSE stream for session ${sessionId}`); - } - - const transport = transports[sessionId]; - await transport.handleRequest(req, res); -}; - -// Set up GET route with conditional auth middleware -if (useOAuth && authMiddleware) { - app.get('/mcp', authMiddleware, mcpGetHandler); -} else { - app.get('/mcp', mcpGetHandler); -} - -// Handle DELETE requests for session termination (according to MCP spec) -const mcpDeleteHandler = async (req: Request, res: Response) => { - const sessionId = req.headers['mcp-session-id'] as string | undefined; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - - console.log(`Received session termination request for session ${sessionId}`); - - try { - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - } catch (error) { - console.error('Error handling session termination:', error); - if (!res.headersSent) { - res.status(500).send('Error processing session termination'); - } - } -}; - -// Set up DELETE route with conditional auth middleware -if (useOAuth && authMiddleware) { - app.delete('/mcp', authMiddleware, mcpDeleteHandler); -} else { - app.delete('/mcp', mcpDeleteHandler); -} - -app.listen(MCP_PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); -}); - -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); diff --git a/typescript-sdk/src/examples/server/sseAndStreamableHttpCompatibleServer.ts b/typescript-sdk/src/examples/server/sseAndStreamableHttpCompatibleServer.ts deleted file mode 100644 index 50e2e51..0000000 --- a/typescript-sdk/src/examples/server/sseAndStreamableHttpCompatibleServer.ts +++ /dev/null @@ -1,260 +0,0 @@ -import express, { Request, Response } from 'express'; -import { randomUUID } from 'node:crypto'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { SSEServerTransport } from '../../server/sse.js'; -import { z } from 'zod'; -import { CallToolResult, isInitializeRequest } from '../../types.js'; -import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; -import cors from 'cors'; - -/** - * This example server demonstrates backwards compatibility with both: - * 1. The deprecated HTTP+SSE transport (protocol version 2024-11-05) - * 2. The Streamable HTTP transport (protocol version 2025-03-26) - * - * It maintains a single MCP server instance but exposes two transport options: - * - /mcp: The new Streamable HTTP endpoint (supports GET/POST/DELETE) - * - /sse: The deprecated SSE endpoint for older clients (GET to establish stream) - * - /messages: The deprecated POST endpoint for older clients (POST to send messages) - */ - -const getServer = () => { - const server = new McpServer( - { - name: 'backwards-compatible-server', - version: '1.0.0' - }, - { capabilities: { logging: {} } } - ); - - // Register a simple tool that sends notifications over time - server.tool( - 'start-notification-stream', - 'Starts sending periodic notifications for testing resumability', - { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(50) - }, - async ({ interval, count }, extra): Promise => { - const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - - while (count === 0 || counter < count) { - counter++; - try { - await server.sendLoggingMessage( - { - level: 'info', - data: `Periodic notification #${counter} at ${new Date().toISOString()}` - }, - extra.sessionId - ); - } catch (error) { - console.error('Error sending notification:', error); - } - // Wait for the specified interval - await sleep(interval); - } - - return { - content: [ - { - type: 'text', - text: `Started sending periodic notifications every ${interval}ms` - } - ] - }; - } - ); - return server; -}; - -// Create Express application -const app = express(); -app.use(express.json()); - -// Configure CORS to expose Mcp-Session-Id header for browser-based clients -app.use( - cors({ - origin: '*', // Allow all origins - adjust as needed for production - exposedHeaders: ['Mcp-Session-Id'] - }) -); - -// Store transports by session ID -const transports: Record = {}; - -//============================================================================= -// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-03-26) -//============================================================================= - -// Handle all MCP Streamable HTTP requests (GET, POST, DELETE) on a single endpoint -app.all('/mcp', async (req: Request, res: Response) => { - console.log(`Received ${req.method} request to /mcp`); - - try { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id'] as string | undefined; - let transport: StreamableHTTPServerTransport; - - if (sessionId && transports[sessionId]) { - // Check if the transport is of the correct type - const existingTransport = transports[sessionId]; - if (existingTransport instanceof StreamableHTTPServerTransport) { - // Reuse existing transport - transport = existingTransport; - } else { - // Transport exists but is not a StreamableHTTPServerTransport (could be SSEServerTransport) - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Session exists but uses a different transport protocol' - }, - id: null - }); - return; - } - } else if (!sessionId && req.method === 'POST' && isInitializeRequest(req.body)) { - const eventStore = new InMemoryEventStore(); - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - eventStore, // Enable resumability - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - console.log(`StreamableHTTP session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - } - }; - - // Connect the transport to the MCP server - const server = getServer(); - await server.connect(transport); - } else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - - // Handle the request with the transport - await transport.handleRequest(req, res, req.body); - } catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); - -//============================================================================= -// DEPRECATED HTTP+SSE TRANSPORT (PROTOCOL VERSION 2024-11-05) -//============================================================================= - -app.get('/sse', async (req: Request, res: Response) => { - console.log('Received GET request to /sse (deprecated SSE transport)'); - const transport = new SSEServerTransport('/messages', res); - transports[transport.sessionId] = transport; - res.on('close', () => { - delete transports[transport.sessionId]; - }); - const server = getServer(); - await server.connect(transport); -}); - -app.post('/messages', async (req: Request, res: Response) => { - const sessionId = req.query.sessionId as string; - let transport: SSEServerTransport; - const existingTransport = transports[sessionId]; - if (existingTransport instanceof SSEServerTransport) { - // Reuse existing transport - transport = existingTransport; - } else { - // Transport exists but is not a SSEServerTransport (could be StreamableHTTPServerTransport) - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Session exists but uses a different transport protocol' - }, - id: null - }); - return; - } - if (transport) { - await transport.handlePostMessage(req, res, req.body); - } else { - res.status(400).send('No transport found for sessionId'); - } -}); - -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Backwards compatible MCP server listening on port ${PORT}`); - console.log(` -============================================== -SUPPORTED TRANSPORT OPTIONS: - -1. Streamable Http(Protocol version: 2025-03-26) - Endpoint: /mcp - Methods: GET, POST, DELETE - Usage: - - Initialize with POST to /mcp - - Establish SSE stream with GET to /mcp - - Send requests with POST to /mcp - - Terminate session with DELETE to /mcp - -2. Http + SSE (Protocol version: 2024-11-05) - Endpoints: /sse (GET) and /messages (POST) - Usage: - - Establish SSE stream with GET to /sse - - Send requests with POST to /messages?sessionId= -============================================== -`); -}); - -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); diff --git a/typescript-sdk/src/examples/server/standaloneSseWithGetStreamableHttp.ts b/typescript-sdk/src/examples/server/standaloneSseWithGetStreamableHttp.ts deleted file mode 100644 index 6229c53..0000000 --- a/typescript-sdk/src/examples/server/standaloneSseWithGetStreamableHttp.ts +++ /dev/null @@ -1,127 +0,0 @@ -import express, { Request, Response } from 'express'; -import { randomUUID } from 'node:crypto'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { isInitializeRequest, ReadResourceResult } from '../../types.js'; - -// Create an MCP server with implementation details -const server = new McpServer({ - name: 'resource-list-changed-notification-server', - version: '1.0.0' -}); - -// Store transports by session ID to send notifications -const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}; - -const addResource = (name: string, content: string) => { - const uri = `https://mcp-example.com/dynamic/${encodeURIComponent(name)}`; - server.resource( - name, - uri, - { mimeType: 'text/plain', description: `Dynamic resource: ${name}` }, - async (): Promise => { - return { - contents: [{ uri, text: content }] - }; - } - ); -}; - -addResource('example-resource', 'Initial content for example-resource'); - -const resourceChangeInterval = setInterval(() => { - const name = randomUUID(); - addResource(name, `Content for ${name}`); -}, 5000); // Change resources every 5 seconds for testing - -const app = express(); -app.use(express.json()); - -app.post('/mcp', async (req: Request, res: Response) => { - console.log('Received MCP request:', req.body); - try { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id'] as string | undefined; - let transport: StreamableHTTPServerTransport; - - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } else if (!sessionId && isInitializeRequest(req.body)) { - // New initialization request - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - - // Connect the transport to the MCP server - await server.connect(transport); - - // Handle the request - the onsessioninitialized callback will store the transport - await transport.handleRequest(req, res, req.body); - return; // Already handled - } else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - - // Handle the request with existing transport - await transport.handleRequest(req, res, req.body); - } catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); - -// Handle GET requests for SSE streams (now using built-in support from StreamableHTTP) -app.get('/mcp', async (req: Request, res: Response) => { - const sessionId = req.headers['mcp-session-id'] as string | undefined; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - - console.log(`Establishing SSE stream for session ${sessionId}`); - const transport = transports[sessionId]; - await transport.handleRequest(req, res); -}); - -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Server listening on port ${PORT}`); -}); - -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - clearInterval(resourceChangeInterval); - await server.close(); - process.exit(0); -}); diff --git a/typescript-sdk/src/examples/server/toolWithSampleServer.ts b/typescript-sdk/src/examples/server/toolWithSampleServer.ts deleted file mode 100644 index ad5a01b..0000000 --- a/typescript-sdk/src/examples/server/toolWithSampleServer.ts +++ /dev/null @@ -1,56 +0,0 @@ -// Run with: npx tsx src/examples/server/toolWithSampleServer.ts - -import { McpServer } from '../../server/mcp.js'; -import { StdioServerTransport } from '../../server/stdio.js'; -import { z } from 'zod'; - -const mcpServer = new McpServer({ - name: 'tools-with-sample-server', - version: '1.0.0' -}); - -// Tool that uses LLM sampling to summarize any text -mcpServer.registerTool( - 'summarize', - { - description: 'Summarize any text using an LLM', - inputSchema: { - text: z.string().describe('Text to summarize') - } - }, - async ({ text }) => { - // Call the LLM through MCP sampling - const response = await mcpServer.server.createMessage({ - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please summarize the following text concisely:\n\n${text}` - } - } - ], - maxTokens: 500 - }); - - return { - content: [ - { - type: 'text', - text: response.content.type === 'text' ? response.content.text : 'Unable to generate summary' - } - ] - }; - } -); - -async function main() { - const transport = new StdioServerTransport(); - await mcpServer.connect(transport); - console.log('MCP server is running...'); -} - -main().catch(error => { - console.error('Server error:', error); - process.exit(1); -}); diff --git a/typescript-sdk/src/examples/shared/inMemoryEventStore.ts b/typescript-sdk/src/examples/shared/inMemoryEventStore.ts deleted file mode 100644 index d4d02eb..0000000 --- a/typescript-sdk/src/examples/shared/inMemoryEventStore.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { JSONRPCMessage } from '../../types.js'; -import { EventStore } from '../../server/streamableHttp.js'; - -/** - * Simple in-memory implementation of the EventStore interface for resumability - * This is primarily intended for examples and testing, not for production use - * where a persistent storage solution would be more appropriate. - */ -export class InMemoryEventStore implements EventStore { - private events: Map = new Map(); - - /** - * Generates a unique event ID for a given stream ID - */ - private generateEventId(streamId: string): string { - return `${streamId}_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`; - } - - /** - * Extracts the stream ID from an event ID - */ - private getStreamIdFromEventId(eventId: string): string { - const parts = eventId.split('_'); - return parts.length > 0 ? parts[0] : ''; - } - - /** - * Stores an event with a generated event ID - * Implements EventStore.storeEvent - */ - async storeEvent(streamId: string, message: JSONRPCMessage): Promise { - const eventId = this.generateEventId(streamId); - this.events.set(eventId, { streamId, message }); - return eventId; - } - - /** - * Replays events that occurred after a specific event ID - * Implements EventStore.replayEventsAfter - */ - async replayEventsAfter( - lastEventId: string, - { send }: { send: (eventId: string, message: JSONRPCMessage) => Promise } - ): Promise { - if (!lastEventId || !this.events.has(lastEventId)) { - return ''; - } - - // Extract the stream ID from the event ID - const streamId = this.getStreamIdFromEventId(lastEventId); - if (!streamId) { - return ''; - } - - let foundLastEvent = false; - - // Sort events by eventId for chronological ordering - const sortedEvents = [...this.events.entries()].sort((a, b) => a[0].localeCompare(b[0])); - - for (const [eventId, { streamId: eventStreamId, message }] of sortedEvents) { - // Only include events from the same stream - if (eventStreamId !== streamId) { - continue; - } - - // Start sending events after we find the lastEventId - if (eventId === lastEventId) { - foundLastEvent = true; - continue; - } - - if (foundLastEvent) { - await send(eventId, message); - } - } - return streamId; - } -} diff --git a/typescript-sdk/src/inMemory.test.ts b/typescript-sdk/src/inMemory.test.ts deleted file mode 100644 index cb758ec..0000000 --- a/typescript-sdk/src/inMemory.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { InMemoryTransport } from './inMemory.js'; -import { JSONRPCMessage } from './types.js'; -import { AuthInfo } from './server/auth/types.js'; - -describe('InMemoryTransport', () => { - let clientTransport: InMemoryTransport; - let serverTransport: InMemoryTransport; - - beforeEach(() => { - [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - }); - - test('should create linked pair', () => { - expect(clientTransport).toBeDefined(); - expect(serverTransport).toBeDefined(); - }); - - test('should start without error', async () => { - await expect(clientTransport.start()).resolves.not.toThrow(); - await expect(serverTransport.start()).resolves.not.toThrow(); - }); - - test('should send message from client to server', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - id: 1 - }; - - let receivedMessage: JSONRPCMessage | undefined; - serverTransport.onmessage = msg => { - receivedMessage = msg; - }; - - await clientTransport.send(message); - expect(receivedMessage).toEqual(message); - }); - - test('should send message with auth info from client to server', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - id: 1 - }; - - const authInfo: AuthInfo = { - token: 'test-token', - clientId: 'test-client', - scopes: ['read', 'write'], - expiresAt: Date.now() / 1000 + 3600 - }; - - let receivedMessage: JSONRPCMessage | undefined; - let receivedAuthInfo: AuthInfo | undefined; - serverTransport.onmessage = (msg, extra) => { - receivedMessage = msg; - receivedAuthInfo = extra?.authInfo; - }; - - await clientTransport.send(message, { authInfo }); - expect(receivedMessage).toEqual(message); - expect(receivedAuthInfo).toEqual(authInfo); - }); - - test('should send message from server to client', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - id: 1 - }; - - let receivedMessage: JSONRPCMessage | undefined; - clientTransport.onmessage = msg => { - receivedMessage = msg; - }; - - await serverTransport.send(message); - expect(receivedMessage).toEqual(message); - }); - - test('should handle close', async () => { - let clientClosed = false; - let serverClosed = false; - - clientTransport.onclose = () => { - clientClosed = true; - }; - - serverTransport.onclose = () => { - serverClosed = true; - }; - - await clientTransport.close(); - expect(clientClosed).toBe(true); - expect(serverClosed).toBe(true); - }); - - test('should throw error when sending after close', async () => { - await clientTransport.close(); - await expect(clientTransport.send({ jsonrpc: '2.0', method: 'test', id: 1 })).rejects.toThrow('Not connected'); - }); - - test('should queue messages sent before start', async () => { - const message: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'test', - id: 1 - }; - - let receivedMessage: JSONRPCMessage | undefined; - serverTransport.onmessage = msg => { - receivedMessage = msg; - }; - - await clientTransport.send(message); - await serverTransport.start(); - expect(receivedMessage).toEqual(message); - }); -}); diff --git a/typescript-sdk/src/inMemory.ts b/typescript-sdk/src/inMemory.ts deleted file mode 100644 index 2606262..0000000 --- a/typescript-sdk/src/inMemory.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { Transport } from './shared/transport.js'; -import { JSONRPCMessage, RequestId } from './types.js'; -import { AuthInfo } from './server/auth/types.js'; - -interface QueuedMessage { - message: JSONRPCMessage; - extra?: { authInfo?: AuthInfo }; -} - -/** - * In-memory transport for creating clients and servers that talk to each other within the same process. - */ -export class InMemoryTransport implements Transport { - private _otherTransport?: InMemoryTransport; - private _messageQueue: QueuedMessage[] = []; - - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: { authInfo?: AuthInfo }) => void; - sessionId?: string; - - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. - */ - static createLinkedPair(): [InMemoryTransport, InMemoryTransport] { - const clientTransport = new InMemoryTransport(); - const serverTransport = new InMemoryTransport(); - clientTransport._otherTransport = serverTransport; - serverTransport._otherTransport = clientTransport; - return [clientTransport, serverTransport]; - } - - async start(): Promise { - // Process any messages that were queued before start was called - while (this._messageQueue.length > 0) { - const queuedMessage = this._messageQueue.shift()!; - this.onmessage?.(queuedMessage.message, queuedMessage.extra); - } - } - - async close(): Promise { - const other = this._otherTransport; - this._otherTransport = undefined; - await other?.close(); - this.onclose?.(); - } - - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - async send(message: JSONRPCMessage, options?: { relatedRequestId?: RequestId; authInfo?: AuthInfo }): Promise { - if (!this._otherTransport) { - throw new Error('Not connected'); - } - - if (this._otherTransport.onmessage) { - this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); - } else { - this._otherTransport._messageQueue.push({ message, extra: { authInfo: options?.authInfo } }); - } - } -} diff --git a/typescript-sdk/src/integration-tests/process-cleanup.test.ts b/typescript-sdk/src/integration-tests/process-cleanup.test.ts deleted file mode 100644 index 8c7c42b..0000000 --- a/typescript-sdk/src/integration-tests/process-cleanup.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { Server } from '../server/index.js'; -import { StdioServerTransport } from '../server/stdio.js'; - -describe('Process cleanup', () => { - jest.setTimeout(5000); // 5 second timeout - - it('should exit cleanly after closing transport', async () => { - const server = new Server( - { - name: 'test-server', - version: '1.0.0' - }, - { - capabilities: {} - } - ); - - const transport = new StdioServerTransport(); - await server.connect(transport); - - // Close the transport - await transport.close(); - - // If we reach here without hanging, the test passes - // The test runner will fail if the process hangs - expect(true).toBe(true); - }); -}); diff --git a/typescript-sdk/src/integration-tests/stateManagementStreamableHttp.test.ts b/typescript-sdk/src/integration-tests/stateManagementStreamableHttp.test.ts deleted file mode 100644 index 629b015..0000000 --- a/typescript-sdk/src/integration-tests/stateManagementStreamableHttp.test.ts +++ /dev/null @@ -1,357 +0,0 @@ -import { createServer, type Server } from 'node:http'; -import { AddressInfo } from 'node:net'; -import { randomUUID } from 'node:crypto'; -import { Client } from '../client/index.js'; -import { StreamableHTTPClientTransport } from '../client/streamableHttp.js'; -import { McpServer } from '../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../server/streamableHttp.js'; -import { - CallToolResultSchema, - ListToolsResultSchema, - ListResourcesResultSchema, - ListPromptsResultSchema, - LATEST_PROTOCOL_VERSION -} from '../types.js'; -import { z } from 'zod'; - -describe('Streamable HTTP Transport Session Management', () => { - // Function to set up the server with optional session management - async function setupServer(withSessionManagement: boolean) { - const server: Server = createServer(); - const mcpServer = new McpServer( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: { - logging: {}, - tools: {}, - resources: {}, - prompts: {} - } - } - ); - - // Add a simple resource - mcpServer.resource('test-resource', '/test', { description: 'A test resource' }, async () => ({ - contents: [ - { - uri: '/test', - text: 'This is a test resource content' - } - ] - })); - - mcpServer.prompt('test-prompt', 'A test prompt', async () => ({ - messages: [ - { - role: 'user', - content: { - type: 'text', - text: 'This is a test prompt' - } - } - ] - })); - - mcpServer.tool( - 'greet', - 'A simple greeting tool', - { - name: z.string().describe('Name to greet').default('World') - }, - async ({ name }) => { - return { - content: [{ type: 'text', text: `Hello, ${name}!` }] - }; - } - ); - - // Create transport with or without session management - const serverTransport = new StreamableHTTPServerTransport({ - sessionIdGenerator: withSessionManagement - ? () => randomUUID() // With session management, generate UUID - : undefined // Without session management, return undefined - }); - - await mcpServer.connect(serverTransport); - - server.on('request', async (req, res) => { - await serverTransport.handleRequest(req, res); - }); - - // Start the server on a random port - const baseUrl = await new Promise(resolve => { - server.listen(0, '127.0.0.1', () => { - const addr = server.address() as AddressInfo; - resolve(new URL(`http://127.0.0.1:${addr.port}`)); - }); - }); - - return { server, mcpServer, serverTransport, baseUrl }; - } - - describe('Stateless Mode', () => { - let server: Server; - let mcpServer: McpServer; - let serverTransport: StreamableHTTPServerTransport; - let baseUrl: URL; - - beforeEach(async () => { - const setup = await setupServer(false); - server = setup.server; - mcpServer = setup.mcpServer; - serverTransport = setup.serverTransport; - baseUrl = setup.baseUrl; - }); - - afterEach(async () => { - // Clean up resources - await mcpServer.close().catch(() => {}); - await serverTransport.close().catch(() => {}); - server.close(); - }); - - it('should support multiple client connections', async () => { - // Create and connect a client - const client1 = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const transport1 = new StreamableHTTPClientTransport(baseUrl); - await client1.connect(transport1); - - // Verify that no session ID was set - expect(transport1.sessionId).toBeUndefined(); - - // List available tools - await client1.request( - { - method: 'tools/list', - params: {} - }, - ListToolsResultSchema - ); - - const client2 = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const transport2 = new StreamableHTTPClientTransport(baseUrl); - await client2.connect(transport2); - - // Verify that no session ID was set - expect(transport2.sessionId).toBeUndefined(); - - // List available tools - await client2.request( - { - method: 'tools/list', - params: {} - }, - ListToolsResultSchema - ); - }); - it('should operate without session management', async () => { - // Create and connect a client - const client = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const transport = new StreamableHTTPClientTransport(baseUrl); - await client.connect(transport); - - // Verify that no session ID was set - expect(transport.sessionId).toBeUndefined(); - - // List available tools - const toolsResult = await client.request( - { - method: 'tools/list', - params: {} - }, - ListToolsResultSchema - ); - - // Verify tools are accessible - expect(toolsResult.tools).toContainEqual( - expect.objectContaining({ - name: 'greet' - }) - ); - - // List available resources - const resourcesResult = await client.request( - { - method: 'resources/list', - params: {} - }, - ListResourcesResultSchema - ); - - // Verify resources result structure - expect(resourcesResult).toHaveProperty('resources'); - - // List available prompts - const promptsResult = await client.request( - { - method: 'prompts/list', - params: {} - }, - ListPromptsResultSchema - ); - - // Verify prompts result structure - expect(promptsResult).toHaveProperty('prompts'); - expect(promptsResult.prompts).toContainEqual( - expect.objectContaining({ - name: 'test-prompt' - }) - ); - - // Call the greeting tool - const greetingResult = await client.request( - { - method: 'tools/call', - params: { - name: 'greet', - arguments: { - name: 'Stateless Transport' - } - } - }, - CallToolResultSchema - ); - - // Verify tool result - expect(greetingResult.content).toEqual([{ type: 'text', text: 'Hello, Stateless Transport!' }]); - - // Clean up - await transport.close(); - }); - - it('should set protocol version after connecting', async () => { - // Create and connect a client - const client = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const transport = new StreamableHTTPClientTransport(baseUrl); - - // Verify protocol version is not set before connecting - expect(transport.protocolVersion).toBeUndefined(); - - await client.connect(transport); - - // Verify protocol version is set after connecting - expect(transport.protocolVersion).toBe(LATEST_PROTOCOL_VERSION); - - // Clean up - await transport.close(); - }); - }); - - describe('Stateful Mode', () => { - let server: Server; - let mcpServer: McpServer; - let serverTransport: StreamableHTTPServerTransport; - let baseUrl: URL; - - beforeEach(async () => { - const setup = await setupServer(true); - server = setup.server; - mcpServer = setup.mcpServer; - serverTransport = setup.serverTransport; - baseUrl = setup.baseUrl; - }); - - afterEach(async () => { - // Clean up resources - await mcpServer.close().catch(() => {}); - await serverTransport.close().catch(() => {}); - server.close(); - }); - - it('should operate with session management', async () => { - // Create and connect a client - const client = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const transport = new StreamableHTTPClientTransport(baseUrl); - await client.connect(transport); - - // Verify that a session ID was set - expect(transport.sessionId).toBeDefined(); - expect(typeof transport.sessionId).toBe('string'); - - // List available tools - const toolsResult = await client.request( - { - method: 'tools/list', - params: {} - }, - ListToolsResultSchema - ); - - // Verify tools are accessible - expect(toolsResult.tools).toContainEqual( - expect.objectContaining({ - name: 'greet' - }) - ); - - // List available resources - const resourcesResult = await client.request( - { - method: 'resources/list', - params: {} - }, - ListResourcesResultSchema - ); - - // Verify resources result structure - expect(resourcesResult).toHaveProperty('resources'); - - // List available prompts - const promptsResult = await client.request( - { - method: 'prompts/list', - params: {} - }, - ListPromptsResultSchema - ); - - // Verify prompts result structure - expect(promptsResult).toHaveProperty('prompts'); - expect(promptsResult.prompts).toContainEqual( - expect.objectContaining({ - name: 'test-prompt' - }) - ); - - // Call the greeting tool - const greetingResult = await client.request( - { - method: 'tools/call', - params: { - name: 'greet', - arguments: { - name: 'Stateful Transport' - } - } - }, - CallToolResultSchema - ); - - // Verify tool result - expect(greetingResult.content).toEqual([{ type: 'text', text: 'Hello, Stateful Transport!' }]); - - // Clean up - await transport.close(); - }); - }); -}); diff --git a/typescript-sdk/src/integration-tests/taskResumability.test.ts b/typescript-sdk/src/integration-tests/taskResumability.test.ts deleted file mode 100644 index d397ffa..0000000 --- a/typescript-sdk/src/integration-tests/taskResumability.test.ts +++ /dev/null @@ -1,270 +0,0 @@ -import { createServer, type Server } from 'node:http'; -import { AddressInfo } from 'node:net'; -import { randomUUID } from 'node:crypto'; -import { Client } from '../client/index.js'; -import { StreamableHTTPClientTransport } from '../client/streamableHttp.js'; -import { McpServer } from '../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../server/streamableHttp.js'; -import { CallToolResultSchema, LoggingMessageNotificationSchema } from '../types.js'; -import { z } from 'zod'; -import { InMemoryEventStore } from '../examples/shared/inMemoryEventStore.js'; - -describe('Transport resumability', () => { - let server: Server; - let mcpServer: McpServer; - let serverTransport: StreamableHTTPServerTransport; - let baseUrl: URL; - let eventStore: InMemoryEventStore; - - beforeEach(async () => { - // Create event store for resumability - eventStore = new InMemoryEventStore(); - - // Create a simple MCP server - mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: { logging: {} } }); - - // Add a simple notification tool that completes quickly - mcpServer.tool( - 'send-notification', - 'Sends a single notification', - { - message: z.string().describe('Message to send').default('Test notification') - }, - async ({ message }, { sendNotification }) => { - // Send notification immediately - await sendNotification({ - method: 'notifications/message', - params: { - level: 'info', - data: message - } - }); - - return { - content: [{ type: 'text', text: 'Notification sent' }] - }; - } - ); - - // Add a long-running tool that sends multiple notifications - mcpServer.tool( - 'run-notifications', - 'Sends multiple notifications over time', - { - count: z.number().describe('Number of notifications to send').default(10), - interval: z.number().describe('Interval between notifications in ms').default(50) - }, - async ({ count, interval }, { sendNotification }) => { - // Send notifications at specified intervals - for (let i = 0; i < count; i++) { - await sendNotification({ - method: 'notifications/message', - params: { - level: 'info', - data: `Notification ${i + 1} of ${count}` - } - }); - - // Wait for the specified interval before sending next notification - if (i < count - 1) { - await new Promise(resolve => setTimeout(resolve, interval)); - } - } - - return { - content: [{ type: 'text', text: `Sent ${count} notifications` }] - }; - } - ); - - // Create a transport with the event store - serverTransport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - eventStore - }); - - // Connect the transport to the MCP server - await mcpServer.connect(serverTransport); - - // Create and start an HTTP server - server = createServer(async (req, res) => { - await serverTransport.handleRequest(req, res); - }); - - // Start the server on a random port - baseUrl = await new Promise(resolve => { - server.listen(0, '127.0.0.1', () => { - const addr = server.address() as AddressInfo; - resolve(new URL(`http://127.0.0.1:${addr.port}`)); - }); - }); - }); - - afterEach(async () => { - // Clean up resources - await mcpServer.close().catch(() => {}); - await serverTransport.close().catch(() => {}); - server.close(); - }); - - it('should store session ID when client connects', async () => { - // Create and connect a client - const client = new Client({ - name: 'test-client', - version: '1.0.0' - }); - - const transport = new StreamableHTTPClientTransport(baseUrl); - await client.connect(transport); - - // Verify session ID was generated - expect(transport.sessionId).toBeDefined(); - - // Clean up - await transport.close(); - }); - - it('should have session ID functionality', async () => { - // The ability to store a session ID when connecting - const client = new Client({ - name: 'test-client-reconnection', - version: '1.0.0' - }); - - const transport = new StreamableHTTPClientTransport(baseUrl); - - // Make sure the client can connect and get a session ID - await client.connect(transport); - expect(transport.sessionId).toBeDefined(); - - // Clean up - await transport.close(); - }); - - // This test demonstrates the capability to resume long-running tools - // across client disconnection/reconnection - it('should resume long-running notifications with lastEventId', async () => { - // Create unique client ID for this test - const clientId = 'test-client-long-running'; - const notifications = []; - let lastEventId: string | undefined; - - // Create first client - const client1 = new Client({ - id: clientId, - name: 'test-client', - version: '1.0.0' - }); - - // Set up notification handler for first client - client1.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - if (notification.method === 'notifications/message') { - notifications.push(notification.params); - } - }); - - // Connect first client - const transport1 = new StreamableHTTPClientTransport(baseUrl); - await client1.connect(transport1); - const sessionId = transport1.sessionId; - expect(sessionId).toBeDefined(); - - // Start a long-running notification stream with tracking of lastEventId - const onLastEventIdUpdate = jest.fn((eventId: string) => { - lastEventId = eventId; - }); - expect(lastEventId).toBeUndefined(); - // Start the notification tool with event tracking using request - const toolPromise = client1.request( - { - method: 'tools/call', - params: { - name: 'run-notifications', - arguments: { - count: 3, - interval: 10 - } - } - }, - CallToolResultSchema, - { - resumptionToken: lastEventId, - onresumptiontoken: onLastEventIdUpdate - } - ); - - // Wait for some notifications to arrive (not all) - shorter wait time - await new Promise(resolve => setTimeout(resolve, 20)); - - // Verify we received some notifications and lastEventId was updated - expect(notifications.length).toBeGreaterThan(0); - expect(notifications.length).toBeLessThan(4); - expect(onLastEventIdUpdate).toHaveBeenCalled(); - expect(lastEventId).toBeDefined(); - - // Disconnect first client without waiting for completion - // When we close the connection, it will cause a ConnectionClosed error for - // any in-progress requests, which is expected behavior - await transport1.close(); - // Save the promise so we can catch it after closing - const catchPromise = toolPromise.catch(err => { - // This error is expected - the connection was intentionally closed - if (err?.code !== -32000) { - // ConnectionClosed error code - console.error('Unexpected error type during transport close:', err); - } - }); - - // Add a short delay to ensure clean disconnect before reconnecting - await new Promise(resolve => setTimeout(resolve, 10)); - - // Wait for the rejection to be handled - await catchPromise; - - // Create second client with same client ID - const client2 = new Client({ - id: clientId, - name: 'test-client', - version: '1.0.0' - }); - - // Set up notification handler for second client - client2.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - if (notification.method === 'notifications/message') { - notifications.push(notification.params); - } - }); - - // Connect second client with same session ID - const transport2 = new StreamableHTTPClientTransport(baseUrl, { - sessionId - }); - await client2.connect(transport2); - - // Resume the notification stream using lastEventId - // This is the key part - we're resuming the same long-running tool using lastEventId - await client2.request( - { - method: 'tools/call', - params: { - name: 'run-notifications', - arguments: { - count: 1, - interval: 5 - } - } - }, - CallToolResultSchema, - { - resumptionToken: lastEventId, // Pass the lastEventId from the previous session - onresumptiontoken: onLastEventIdUpdate - } - ); - - // Verify we eventually received at leaset a few motifications - expect(notifications.length).toBeGreaterThan(1); - - // Clean up - await transport2.close(); - }); -}); diff --git a/typescript-sdk/src/server/auth/clients.ts b/typescript-sdk/src/server/auth/clients.ts deleted file mode 100644 index 4e3f8e1..0000000 --- a/typescript-sdk/src/server/auth/clients.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { OAuthClientInformationFull } from '../../shared/auth.js'; - -/** - * Stores information about registered OAuth clients for this server. - */ -export interface OAuthRegisteredClientsStore { - /** - * Returns information about a registered client, based on its ID. - */ - getClient(clientId: string): OAuthClientInformationFull | undefined | Promise; - - /** - * Registers a new client with the server. The client ID and secret will be automatically generated by the library. A modified version of the client information can be returned to reflect specific values enforced by the server. - * - * NOTE: Implementations should NOT delete expired client secrets in-place. Auth middleware provided by this library will automatically check the `client_secret_expires_at` field and reject requests with expired secrets. Any custom logic for authenticating clients should check the `client_secret_expires_at` field as well. - * - * If unimplemented, dynamic client registration is unsupported. - */ - registerClient?( - client: Omit - ): OAuthClientInformationFull | Promise; -} diff --git a/typescript-sdk/src/server/auth/errors.ts b/typescript-sdk/src/server/auth/errors.ts deleted file mode 100644 index e6871a1..0000000 --- a/typescript-sdk/src/server/auth/errors.ts +++ /dev/null @@ -1,203 +0,0 @@ -import { OAuthErrorResponse } from '../../shared/auth.js'; - -/** - * Base class for all OAuth errors - */ -export class OAuthError extends Error { - static errorCode: string; - - constructor( - message: string, - public readonly errorUri?: string - ) { - super(message); - this.name = this.constructor.name; - } - - /** - * Converts the error to a standard OAuth error response object - */ - toResponseObject(): OAuthErrorResponse { - const response: OAuthErrorResponse = { - error: this.errorCode, - error_description: this.message - }; - - if (this.errorUri) { - response.error_uri = this.errorUri; - } - - return response; - } - - get errorCode(): string { - return (this.constructor as typeof OAuthError).errorCode; - } -} - -/** - * Invalid request error - The request is missing a required parameter, - * includes an invalid parameter value, includes a parameter more than once, - * or is otherwise malformed. - */ -export class InvalidRequestError extends OAuthError { - static errorCode = 'invalid_request'; -} - -/** - * Invalid client error - Client authentication failed (e.g., unknown client, no client - * authentication included, or unsupported authentication method). - */ -export class InvalidClientError extends OAuthError { - static errorCode = 'invalid_client'; -} - -/** - * Invalid grant error - The provided authorization grant or refresh token is - * invalid, expired, revoked, does not match the redirection URI used in the - * authorization request, or was issued to another client. - */ -export class InvalidGrantError extends OAuthError { - static errorCode = 'invalid_grant'; -} - -/** - * Unauthorized client error - The authenticated client is not authorized to use - * this authorization grant type. - */ -export class UnauthorizedClientError extends OAuthError { - static errorCode = 'unauthorized_client'; -} - -/** - * Unsupported grant type error - The authorization grant type is not supported - * by the authorization server. - */ -export class UnsupportedGrantTypeError extends OAuthError { - static errorCode = 'unsupported_grant_type'; -} - -/** - * Invalid scope error - The requested scope is invalid, unknown, malformed, or - * exceeds the scope granted by the resource owner. - */ -export class InvalidScopeError extends OAuthError { - static errorCode = 'invalid_scope'; -} - -/** - * Access denied error - The resource owner or authorization server denied the request. - */ -export class AccessDeniedError extends OAuthError { - static errorCode = 'access_denied'; -} - -/** - * Server error - The authorization server encountered an unexpected condition - * that prevented it from fulfilling the request. - */ -export class ServerError extends OAuthError { - static errorCode = 'server_error'; -} - -/** - * Temporarily unavailable error - The authorization server is currently unable to - * handle the request due to a temporary overloading or maintenance of the server. - */ -export class TemporarilyUnavailableError extends OAuthError { - static errorCode = 'temporarily_unavailable'; -} - -/** - * Unsupported response type error - The authorization server does not support - * obtaining an authorization code using this method. - */ -export class UnsupportedResponseTypeError extends OAuthError { - static errorCode = 'unsupported_response_type'; -} - -/** - * Unsupported token type error - The authorization server does not support - * the requested token type. - */ -export class UnsupportedTokenTypeError extends OAuthError { - static errorCode = 'unsupported_token_type'; -} - -/** - * Invalid token error - The access token provided is expired, revoked, malformed, - * or invalid for other reasons. - */ -export class InvalidTokenError extends OAuthError { - static errorCode = 'invalid_token'; -} - -/** - * Method not allowed error - The HTTP method used is not allowed for this endpoint. - * (Custom, non-standard error) - */ -export class MethodNotAllowedError extends OAuthError { - static errorCode = 'method_not_allowed'; -} - -/** - * Too many requests error - Rate limit exceeded. - * (Custom, non-standard error based on RFC 6585) - */ -export class TooManyRequestsError extends OAuthError { - static errorCode = 'too_many_requests'; -} - -/** - * Invalid client metadata error - The client metadata is invalid. - * (Custom error for dynamic client registration - RFC 7591) - */ -export class InvalidClientMetadataError extends OAuthError { - static errorCode = 'invalid_client_metadata'; -} - -/** - * Insufficient scope error - The request requires higher privileges than provided by the access token. - */ -export class InsufficientScopeError extends OAuthError { - static errorCode = 'insufficient_scope'; -} - -/** - * A utility class for defining one-off error codes - */ -export class CustomOAuthError extends OAuthError { - constructor( - private readonly customErrorCode: string, - message: string, - errorUri?: string - ) { - super(message, errorUri); - } - - get errorCode(): string { - return this.customErrorCode; - } -} - -/** - * A full list of all OAuthErrors, enabling parsing from error responses - */ -export const OAUTH_ERRORS = { - [InvalidRequestError.errorCode]: InvalidRequestError, - [InvalidClientError.errorCode]: InvalidClientError, - [InvalidGrantError.errorCode]: InvalidGrantError, - [UnauthorizedClientError.errorCode]: UnauthorizedClientError, - [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, - [InvalidScopeError.errorCode]: InvalidScopeError, - [AccessDeniedError.errorCode]: AccessDeniedError, - [ServerError.errorCode]: ServerError, - [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, - [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, - [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, - [InvalidTokenError.errorCode]: InvalidTokenError, - [MethodNotAllowedError.errorCode]: MethodNotAllowedError, - [TooManyRequestsError.errorCode]: TooManyRequestsError, - [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, - [InsufficientScopeError.errorCode]: InsufficientScopeError -} as const; diff --git a/typescript-sdk/src/server/auth/handlers/authorize.test.ts b/typescript-sdk/src/server/auth/handlers/authorize.test.ts deleted file mode 100644 index 5dabd19..0000000 --- a/typescript-sdk/src/server/auth/handlers/authorize.test.ts +++ /dev/null @@ -1,326 +0,0 @@ -import { authorizationHandler, AuthorizationHandlerOptions } from './authorize.js'; -import { OAuthServerProvider, AuthorizationParams } from '../provider.js'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { OAuthClientInformationFull, OAuthTokens } from '../../../shared/auth.js'; -import express, { Response } from 'express'; -import supertest from 'supertest'; -import { AuthInfo } from '../types.js'; -import { InvalidTokenError } from '../errors.js'; - -describe('Authorization Handler', () => { - // Mock client data - const validClient: OAuthClientInformationFull = { - client_id: 'valid-client', - client_secret: 'valid-secret', - redirect_uris: ['https://example.com/callback'], - scope: 'profile email' - }; - - const multiRedirectClient: OAuthClientInformationFull = { - client_id: 'multi-redirect-client', - client_secret: 'valid-secret', - redirect_uris: ['https://example.com/callback1', 'https://example.com/callback2'], - scope: 'profile email' - }; - - // Mock client store - const mockClientStore: OAuthRegisteredClientsStore = { - async getClient(clientId: string): Promise { - if (clientId === 'valid-client') { - return validClient; - } else if (clientId === 'multi-redirect-client') { - return multiRedirectClient; - } - return undefined; - } - }; - - // Mock provider - const mockProvider: OAuthServerProvider = { - clientsStore: mockClientStore, - - async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise { - // Mock implementation - redirects to redirectUri with code and state - const redirectUrl = new URL(params.redirectUri); - redirectUrl.searchParams.set('code', 'mock_auth_code'); - if (params.state) { - redirectUrl.searchParams.set('state', params.state); - } - res.redirect(302, redirectUrl.toString()); - }, - - async challengeForAuthorizationCode(): Promise { - return 'mock_challenge'; - }, - - async exchangeAuthorizationCode(): Promise { - return { - access_token: 'mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'mock_refresh_token' - }; - }, - - async exchangeRefreshToken(): Promise { - return { - access_token: 'new_mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'new_mock_refresh_token' - }; - }, - - async verifyAccessToken(token: string): Promise { - if (token === 'valid_token') { - return { - token, - clientId: 'valid-client', - scopes: ['read', 'write'], - expiresAt: Date.now() / 1000 + 3600 - }; - } - throw new InvalidTokenError('Token is invalid or expired'); - }, - - async revokeToken(): Promise { - // Do nothing in mock - } - }; - - // Setup express app with handler - let app: express.Express; - let options: AuthorizationHandlerOptions; - - beforeEach(() => { - app = express(); - options = { provider: mockProvider }; - const handler = authorizationHandler(options); - app.use('/authorize', handler); - }); - - describe('HTTP method validation', () => { - it('rejects non-GET/POST methods', async () => { - const response = await supertest(app).put('/authorize').query({ client_id: 'valid-client' }); - - expect(response.status).toBe(405); // Method not allowed response from handler - }); - }); - - describe('Client validation', () => { - it('requires client_id parameter', async () => { - const response = await supertest(app).get('/authorize'); - - expect(response.status).toBe(400); - expect(response.text).toContain('client_id'); - }); - - it('validates that client exists', async () => { - const response = await supertest(app).get('/authorize').query({ client_id: 'nonexistent-client' }); - - expect(response.status).toBe(400); - }); - }); - - describe('Redirect URI validation', () => { - it('uses the only redirect_uri if client has just one and none provided', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256' - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.origin + location.pathname).toBe('https://example.com/callback'); - }); - - it('requires redirect_uri if client has multiple', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'multi-redirect-client', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256' - }); - - expect(response.status).toBe(400); - }); - - it('validates redirect_uri against client registered URIs', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - redirect_uri: 'https://malicious.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256' - }); - - expect(response.status).toBe(400); - }); - - it('accepts valid redirect_uri that client registered with', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256' - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.origin + location.pathname).toBe('https://example.com/callback'); - }); - }); - - describe('Authorization request validation', () => { - it('requires response_type=code', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'token', // invalid - we only support code flow - code_challenge: 'challenge123', - code_challenge_method: 'S256' - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.searchParams.get('error')).toBe('invalid_request'); - }); - - it('requires code_challenge parameter', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge_method: 'S256' - // Missing code_challenge - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.searchParams.get('error')).toBe('invalid_request'); - }); - - it('requires code_challenge_method=S256', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'plain' // Only S256 is supported - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.searchParams.get('error')).toBe('invalid_request'); - }); - }); - - describe('Scope validation', () => { - it('validates requested scopes against client registered scopes', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256', - scope: 'profile email admin' // 'admin' not in client scopes - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.searchParams.get('error')).toBe('invalid_scope'); - }); - - it('accepts valid scopes subset', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256', - scope: 'profile' // subset of client scopes - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.searchParams.has('code')).toBe(true); - }); - }); - - describe('Resource parameter validation', () => { - it('propagates resource parameter', async () => { - const mockProviderWithResource = jest.spyOn(mockProvider, 'authorize'); - - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256', - resource: 'https://api.example.com/resource' - }); - - expect(response.status).toBe(302); - expect(mockProviderWithResource).toHaveBeenCalledWith( - validClient, - expect.objectContaining({ - resource: new URL('https://api.example.com/resource'), - redirectUri: 'https://example.com/callback', - codeChallenge: 'challenge123' - }), - expect.any(Object) - ); - }); - }); - - describe('Successful authorization', () => { - it('handles successful authorization with all parameters', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256', - scope: 'profile email', - state: 'xyz789' - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.origin + location.pathname).toBe('https://example.com/callback'); - expect(location.searchParams.get('code')).toBe('mock_auth_code'); - expect(location.searchParams.get('state')).toBe('xyz789'); - }); - - it('preserves state parameter in response', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256', - state: 'state-value-123' - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.searchParams.get('state')).toBe('state-value-123'); - }); - - it('handles POST requests the same as GET', async () => { - const response = await supertest(app).post('/authorize').type('form').send({ - client_id: 'valid-client', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256' - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.searchParams.has('code')).toBe(true); - }); - }); -}); diff --git a/typescript-sdk/src/server/auth/handlers/authorize.ts b/typescript-sdk/src/server/auth/handlers/authorize.ts deleted file mode 100644 index 14c7121..0000000 --- a/typescript-sdk/src/server/auth/handlers/authorize.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { RequestHandler } from 'express'; -import { z } from 'zod'; -import express from 'express'; -import { OAuthServerProvider } from '../provider.js'; -import { rateLimit, Options as RateLimitOptions } from 'express-rate-limit'; -import { allowedMethods } from '../middleware/allowedMethods.js'; -import { InvalidRequestError, InvalidClientError, InvalidScopeError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; - -export type AuthorizationHandlerOptions = { - provider: OAuthServerProvider; - /** - * Rate limiting configuration for the authorization endpoint. - * Set to false to disable rate limiting for this endpoint. - */ - rateLimit?: Partial | false; -}; - -// Parameters that must be validated in order to issue redirects. -const ClientAuthorizationParamsSchema = z.object({ - client_id: z.string(), - redirect_uri: z - .string() - .optional() - .refine(value => value === undefined || URL.canParse(value), { message: 'redirect_uri must be a valid URL' }) -}); - -// Parameters that must be validated for a successful authorization request. Failure can be reported to the redirect URI. -const RequestAuthorizationParamsSchema = z.object({ - response_type: z.literal('code'), - code_challenge: z.string(), - code_challenge_method: z.literal('S256'), - scope: z.string().optional(), - state: z.string().optional(), - resource: z.string().url().optional() -}); - -export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler { - // Create a router to apply middleware - const router = express.Router(); - router.use(allowedMethods(['GET', 'POST'])); - router.use(express.urlencoded({ extended: false })); - - // Apply rate limiting unless explicitly disabled - if (rateLimitConfig !== false) { - router.use( - rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 100, // 100 requests per windowMs - standardHeaders: true, - legacyHeaders: false, - message: new TooManyRequestsError('You have exceeded the rate limit for authorization requests').toResponseObject(), - ...rateLimitConfig - }) - ); - } - - router.all('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - - // In the authorization flow, errors are split into two categories: - // 1. Pre-redirect errors (direct response with 400) - // 2. Post-redirect errors (redirect with error parameters) - - // Phase 1: Validate client_id and redirect_uri. Any errors here must be direct responses. - let client_id, redirect_uri, client; - try { - const result = ClientAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); - if (!result.success) { - throw new InvalidRequestError(result.error.message); - } - - client_id = result.data.client_id; - redirect_uri = result.data.redirect_uri; - - client = await provider.clientsStore.getClient(client_id); - if (!client) { - throw new InvalidClientError('Invalid client_id'); - } - - if (redirect_uri !== undefined) { - if (!client.redirect_uris.includes(redirect_uri)) { - throw new InvalidRequestError('Unregistered redirect_uri'); - } - } else if (client.redirect_uris.length === 1) { - redirect_uri = client.redirect_uris[0]; - } else { - throw new InvalidRequestError('redirect_uri must be specified when client has multiple registered URIs'); - } - } catch (error) { - // Pre-redirect errors - return direct response - // - // These don't need to be JSON encoded, as they'll be displayed in a user - // agent, but OTOH they all represent exceptional situations (arguably, - // "programmer error"), so presenting a nice HTML page doesn't help the - // user anyway. - if (error instanceof OAuthError) { - const status = error instanceof ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - - return; - } - - // Phase 2: Validate other parameters. Any errors here should go into redirect responses. - let state; - try { - // Parse and validate authorization parameters - const parseResult = RequestAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); - if (!parseResult.success) { - throw new InvalidRequestError(parseResult.error.message); - } - - const { scope, code_challenge, resource } = parseResult.data; - state = parseResult.data.state; - - // Validate scopes - let requestedScopes: string[] = []; - if (scope !== undefined) { - requestedScopes = scope.split(' '); - const allowedScopes = new Set(client.scope?.split(' ')); - - // Check each requested scope against allowed scopes - for (const scope of requestedScopes) { - if (!allowedScopes.has(scope)) { - throw new InvalidScopeError(`Client was not registered with scope ${scope}`); - } - } - } - - // All validation passed, proceed with authorization - await provider.authorize( - client, - { - state, - scopes: requestedScopes, - redirectUri: redirect_uri, - codeChallenge: code_challenge, - resource: resource ? new URL(resource) : undefined - }, - res - ); - } catch (error) { - // Post-redirect errors - redirect with error parameters - if (error instanceof OAuthError) { - res.redirect(302, createErrorRedirect(redirect_uri, error, state)); - } else { - const serverError = new ServerError('Internal Server Error'); - res.redirect(302, createErrorRedirect(redirect_uri, serverError, state)); - } - } - }); - - return router; -} - -/** - * Helper function to create redirect URL with error parameters - */ -function createErrorRedirect(redirectUri: string, error: OAuthError, state?: string): string { - const errorUrl = new URL(redirectUri); - errorUrl.searchParams.set('error', error.errorCode); - errorUrl.searchParams.set('error_description', error.message); - if (error.errorUri) { - errorUrl.searchParams.set('error_uri', error.errorUri); - } - if (state) { - errorUrl.searchParams.set('state', state); - } - return errorUrl.href; -} diff --git a/typescript-sdk/src/server/auth/handlers/metadata.test.ts b/typescript-sdk/src/server/auth/handlers/metadata.test.ts deleted file mode 100644 index 32feb64..0000000 --- a/typescript-sdk/src/server/auth/handlers/metadata.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { metadataHandler } from './metadata.js'; -import { OAuthMetadata } from '../../../shared/auth.js'; -import express from 'express'; -import supertest from 'supertest'; - -describe('Metadata Handler', () => { - const exampleMetadata: OAuthMetadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - registration_endpoint: 'https://auth.example.com/register', - revocation_endpoint: 'https://auth.example.com/revoke', - scopes_supported: ['profile', 'email'], - response_types_supported: ['code'], - grant_types_supported: ['authorization_code', 'refresh_token'], - token_endpoint_auth_methods_supported: ['client_secret_basic'], - code_challenge_methods_supported: ['S256'] - }; - - let app: express.Express; - - beforeEach(() => { - // Setup express app with metadata handler - app = express(); - app.use('/.well-known/oauth-authorization-server', metadataHandler(exampleMetadata)); - }); - - it('requires GET method', async () => { - const response = await supertest(app).post('/.well-known/oauth-authorization-server').send({}); - - expect(response.status).toBe(405); - expect(response.headers.allow).toBe('GET'); - expect(response.body).toEqual({ - error: 'method_not_allowed', - error_description: 'The method POST is not allowed for this endpoint' - }); - }); - - it('returns the metadata object', async () => { - const response = await supertest(app).get('/.well-known/oauth-authorization-server'); - - expect(response.status).toBe(200); - expect(response.body).toEqual(exampleMetadata); - }); - - it('includes CORS headers in response', async () => { - const response = await supertest(app).get('/.well-known/oauth-authorization-server').set('Origin', 'https://example.com'); - - expect(response.header['access-control-allow-origin']).toBe('*'); - }); - - it('supports OPTIONS preflight requests', async () => { - const response = await supertest(app) - .options('/.well-known/oauth-authorization-server') - .set('Origin', 'https://example.com') - .set('Access-Control-Request-Method', 'GET'); - - expect(response.status).toBe(204); - expect(response.header['access-control-allow-origin']).toBe('*'); - }); - - it('works with minimal metadata', async () => { - // Setup a new express app with minimal metadata - const minimalApp = express(); - const minimalMetadata: OAuthMetadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'] - }; - minimalApp.use('/.well-known/oauth-authorization-server', metadataHandler(minimalMetadata)); - - const response = await supertest(minimalApp).get('/.well-known/oauth-authorization-server'); - - expect(response.status).toBe(200); - expect(response.body).toEqual(minimalMetadata); - }); -}); diff --git a/typescript-sdk/src/server/auth/handlers/metadata.ts b/typescript-sdk/src/server/auth/handlers/metadata.ts deleted file mode 100644 index d8ca0e6..0000000 --- a/typescript-sdk/src/server/auth/handlers/metadata.ts +++ /dev/null @@ -1,19 +0,0 @@ -import express, { RequestHandler } from 'express'; -import { OAuthMetadata, OAuthProtectedResourceMetadata } from '../../../shared/auth.js'; -import cors from 'cors'; -import { allowedMethods } from '../middleware/allowedMethods.js'; - -export function metadataHandler(metadata: OAuthMetadata | OAuthProtectedResourceMetadata): RequestHandler { - // Nested router so we can configure middleware and restrict HTTP method - const router = express.Router(); - - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use(cors()); - - router.use(allowedMethods(['GET'])); - router.get('/', (req, res) => { - res.status(200).json(metadata); - }); - - return router; -} diff --git a/typescript-sdk/src/server/auth/handlers/register.test.ts b/typescript-sdk/src/server/auth/handlers/register.test.ts deleted file mode 100644 index c482143..0000000 --- a/typescript-sdk/src/server/auth/handlers/register.test.ts +++ /dev/null @@ -1,271 +0,0 @@ -import { clientRegistrationHandler, ClientRegistrationHandlerOptions } from './register.js'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { OAuthClientInformationFull, OAuthClientMetadata } from '../../../shared/auth.js'; -import express from 'express'; -import supertest from 'supertest'; - -describe('Client Registration Handler', () => { - // Mock client store with registration support - const mockClientStoreWithRegistration: OAuthRegisteredClientsStore = { - async getClient(_clientId: string): Promise { - return undefined; - }, - - async registerClient(client: OAuthClientInformationFull): Promise { - // Return the client info as-is in the mock - return client; - } - }; - - // Mock client store without registration support - const mockClientStoreWithoutRegistration: OAuthRegisteredClientsStore = { - async getClient(_clientId: string): Promise { - return undefined; - } - // No registerClient method - }; - - describe('Handler creation', () => { - it('throws error if client store does not support registration', () => { - const options: ClientRegistrationHandlerOptions = { - clientsStore: mockClientStoreWithoutRegistration - }; - - expect(() => clientRegistrationHandler(options)).toThrow('does not support registering clients'); - }); - - it('creates handler if client store supports registration', () => { - const options: ClientRegistrationHandlerOptions = { - clientsStore: mockClientStoreWithRegistration - }; - - expect(() => clientRegistrationHandler(options)).not.toThrow(); - }); - }); - - describe('Request handling', () => { - let app: express.Express; - let spyRegisterClient: jest.SpyInstance; - - beforeEach(() => { - // Setup express app with registration handler - app = express(); - const options: ClientRegistrationHandlerOptions = { - clientsStore: mockClientStoreWithRegistration, - clientSecretExpirySeconds: 86400 // 1 day for testing - }; - - app.use('/register', clientRegistrationHandler(options)); - - // Spy on the registerClient method - spyRegisterClient = jest.spyOn(mockClientStoreWithRegistration, 'registerClient'); - }); - - afterEach(() => { - spyRegisterClient.mockRestore(); - }); - - it('requires POST method', async () => { - const response = await supertest(app) - .get('/register') - .send({ - redirect_uris: ['https://example.com/callback'] - }); - - expect(response.status).toBe(405); - expect(response.headers.allow).toBe('POST'); - expect(response.body).toEqual({ - error: 'method_not_allowed', - error_description: 'The method GET is not allowed for this endpoint' - }); - expect(spyRegisterClient).not.toHaveBeenCalled(); - }); - - it('validates required client metadata', async () => { - const response = await supertest(app).post('/register').send({ - // Missing redirect_uris (required) - client_name: 'Test Client' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_client_metadata'); - expect(spyRegisterClient).not.toHaveBeenCalled(); - }); - - it('validates redirect URIs format', async () => { - const response = await supertest(app) - .post('/register') - .send({ - redirect_uris: ['invalid-url'] // Invalid URL format - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_client_metadata'); - expect(response.body.error_description).toContain('redirect_uris'); - expect(spyRegisterClient).not.toHaveBeenCalled(); - }); - - it('successfully registers client with minimal metadata', async () => { - const clientMetadata: OAuthClientMetadata = { - redirect_uris: ['https://example.com/callback'] - }; - - const response = await supertest(app).post('/register').send(clientMetadata); - - expect(response.status).toBe(201); - - // Verify the generated client information - expect(response.body.client_id).toBeDefined(); - expect(response.body.client_secret).toBeDefined(); - expect(response.body.client_id_issued_at).toBeDefined(); - expect(response.body.client_secret_expires_at).toBeDefined(); - expect(response.body.redirect_uris).toEqual(['https://example.com/callback']); - - // Verify client was registered - expect(spyRegisterClient).toHaveBeenCalledTimes(1); - }); - - it('sets client_secret to undefined for token_endpoint_auth_method=none', async () => { - const clientMetadata: OAuthClientMetadata = { - redirect_uris: ['https://example.com/callback'], - token_endpoint_auth_method: 'none' - }; - - const response = await supertest(app).post('/register').send(clientMetadata); - - expect(response.status).toBe(201); - expect(response.body.client_secret).toBeUndefined(); - expect(response.body.client_secret_expires_at).toBeUndefined(); - }); - - it('sets client_secret_expires_at for public clients only', async () => { - // Test for public client (token_endpoint_auth_method not 'none') - const publicClientMetadata: OAuthClientMetadata = { - redirect_uris: ['https://example.com/callback'], - token_endpoint_auth_method: 'client_secret_basic' - }; - - const publicResponse = await supertest(app).post('/register').send(publicClientMetadata); - - expect(publicResponse.status).toBe(201); - expect(publicResponse.body.client_secret).toBeDefined(); - expect(publicResponse.body.client_secret_expires_at).toBeDefined(); - - // Test for non-public client (token_endpoint_auth_method is 'none') - const nonPublicClientMetadata: OAuthClientMetadata = { - redirect_uris: ['https://example.com/callback'], - token_endpoint_auth_method: 'none' - }; - - const nonPublicResponse = await supertest(app).post('/register').send(nonPublicClientMetadata); - - expect(nonPublicResponse.status).toBe(201); - expect(nonPublicResponse.body.client_secret).toBeUndefined(); - expect(nonPublicResponse.body.client_secret_expires_at).toBeUndefined(); - }); - - it('sets expiry based on clientSecretExpirySeconds', async () => { - // Create handler with custom expiry time - const customApp = express(); - const options: ClientRegistrationHandlerOptions = { - clientsStore: mockClientStoreWithRegistration, - clientSecretExpirySeconds: 3600 // 1 hour - }; - - customApp.use('/register', clientRegistrationHandler(options)); - - const response = await supertest(customApp) - .post('/register') - .send({ - redirect_uris: ['https://example.com/callback'] - }); - - expect(response.status).toBe(201); - - // Verify the expiration time (~1 hour from now) - const issuedAt = response.body.client_id_issued_at; - const expiresAt = response.body.client_secret_expires_at; - expect(expiresAt - issuedAt).toBe(3600); - }); - - it('sets no expiry when clientSecretExpirySeconds=0', async () => { - // Create handler with no expiry - const customApp = express(); - const options: ClientRegistrationHandlerOptions = { - clientsStore: mockClientStoreWithRegistration, - clientSecretExpirySeconds: 0 // No expiry - }; - - customApp.use('/register', clientRegistrationHandler(options)); - - const response = await supertest(customApp) - .post('/register') - .send({ - redirect_uris: ['https://example.com/callback'] - }); - - expect(response.status).toBe(201); - expect(response.body.client_secret_expires_at).toBe(0); - }); - - it('sets no client_id when clientIdGeneration=false', async () => { - // Create handler with no expiry - const customApp = express(); - const options: ClientRegistrationHandlerOptions = { - clientsStore: mockClientStoreWithRegistration, - clientIdGeneration: false - }; - - customApp.use('/register', clientRegistrationHandler(options)); - - const response = await supertest(customApp) - .post('/register') - .send({ - redirect_uris: ['https://example.com/callback'] - }); - - expect(response.status).toBe(201); - expect(response.body.client_id).toBeUndefined(); - expect(response.body.client_id_issued_at).toBeUndefined(); - }); - - it('handles client with all metadata fields', async () => { - const fullClientMetadata: OAuthClientMetadata = { - redirect_uris: ['https://example.com/callback'], - token_endpoint_auth_method: 'client_secret_basic', - grant_types: ['authorization_code', 'refresh_token'], - response_types: ['code'], - client_name: 'Test Client', - client_uri: 'https://example.com', - logo_uri: 'https://example.com/logo.png', - scope: 'profile email', - contacts: ['dev@example.com'], - tos_uri: 'https://example.com/tos', - policy_uri: 'https://example.com/privacy', - jwks_uri: 'https://example.com/jwks', - software_id: 'test-software', - software_version: '1.0.0' - }; - - const response = await supertest(app).post('/register').send(fullClientMetadata); - - expect(response.status).toBe(201); - - // Verify all metadata was preserved - Object.entries(fullClientMetadata).forEach(([key, value]) => { - expect(response.body[key]).toEqual(value); - }); - }); - - it('includes CORS headers in response', async () => { - const response = await supertest(app) - .post('/register') - .set('Origin', 'https://example.com') - .send({ - redirect_uris: ['https://example.com/callback'] - }); - - expect(response.header['access-control-allow-origin']).toBe('*'); - }); - }); -}); diff --git a/typescript-sdk/src/server/auth/handlers/register.ts b/typescript-sdk/src/server/auth/handlers/register.ts deleted file mode 100644 index 1830619..0000000 --- a/typescript-sdk/src/server/auth/handlers/register.ts +++ /dev/null @@ -1,119 +0,0 @@ -import express, { RequestHandler } from 'express'; -import { OAuthClientInformationFull, OAuthClientMetadataSchema } from '../../../shared/auth.js'; -import crypto from 'node:crypto'; -import cors from 'cors'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { rateLimit, Options as RateLimitOptions } from 'express-rate-limit'; -import { allowedMethods } from '../middleware/allowedMethods.js'; -import { InvalidClientMetadataError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; - -export type ClientRegistrationHandlerOptions = { - /** - * A store used to save information about dynamically registered OAuth clients. - */ - clientsStore: OAuthRegisteredClientsStore; - - /** - * The number of seconds after which to expire issued client secrets, or 0 to prevent expiration of client secrets (not recommended). - * - * If not set, defaults to 30 days. - */ - clientSecretExpirySeconds?: number; - - /** - * Rate limiting configuration for the client registration endpoint. - * Set to false to disable rate limiting for this endpoint. - * Registration endpoints are particularly sensitive to abuse and should be rate limited. - */ - rateLimit?: Partial | false; - - /** - * Whether to generate a client ID before calling the client registration endpoint. - * - * If not set, defaults to true. - */ - clientIdGeneration?: boolean; -}; - -const DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS = 30 * 24 * 60 * 60; // 30 days - -export function clientRegistrationHandler({ - clientsStore, - clientSecretExpirySeconds = DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS, - rateLimit: rateLimitConfig, - clientIdGeneration = true -}: ClientRegistrationHandlerOptions): RequestHandler { - if (!clientsStore.registerClient) { - throw new Error('Client registration store does not support registering clients'); - } - - // Nested router so we can configure middleware and restrict HTTP method - const router = express.Router(); - - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use(cors()); - - router.use(allowedMethods(['POST'])); - router.use(express.json()); - - // Apply rate limiting unless explicitly disabled - stricter limits for registration - if (rateLimitConfig !== false) { - router.use( - rateLimit({ - windowMs: 60 * 60 * 1000, // 1 hour - max: 20, // 20 requests per hour - stricter as registration is sensitive - standardHeaders: true, - legacyHeaders: false, - message: new TooManyRequestsError('You have exceeded the rate limit for client registration requests').toResponseObject(), - ...rateLimitConfig - }) - ); - } - - router.post('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - - try { - const parseResult = OAuthClientMetadataSchema.safeParse(req.body); - if (!parseResult.success) { - throw new InvalidClientMetadataError(parseResult.error.message); - } - - const clientMetadata = parseResult.data; - const isPublicClient = clientMetadata.token_endpoint_auth_method === 'none'; - - // Generate client credentials - const clientSecret = isPublicClient ? undefined : crypto.randomBytes(32).toString('hex'); - const clientIdIssuedAt = Math.floor(Date.now() / 1000); - - // Calculate client secret expiry time - const clientsDoExpire = clientSecretExpirySeconds > 0; - const secretExpiryTime = clientsDoExpire ? clientIdIssuedAt + clientSecretExpirySeconds : 0; - const clientSecretExpiresAt = isPublicClient ? undefined : secretExpiryTime; - - let clientInfo: Omit & { client_id?: string } = { - ...clientMetadata, - client_secret: clientSecret, - client_secret_expires_at: clientSecretExpiresAt - }; - - if (clientIdGeneration) { - clientInfo.client_id = crypto.randomUUID(); - clientInfo.client_id_issued_at = clientIdIssuedAt; - } - - clientInfo = await clientsStore.registerClient!(clientInfo); - res.status(201).json(clientInfo); - } catch (error) { - if (error instanceof OAuthError) { - const status = error instanceof ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }); - - return router; -} diff --git a/typescript-sdk/src/server/auth/handlers/revoke.test.ts b/typescript-sdk/src/server/auth/handlers/revoke.test.ts deleted file mode 100644 index 594b689..0000000 --- a/typescript-sdk/src/server/auth/handlers/revoke.test.ts +++ /dev/null @@ -1,229 +0,0 @@ -import { revocationHandler, RevocationHandlerOptions } from './revoke.js'; -import { OAuthServerProvider, AuthorizationParams } from '../provider.js'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../../shared/auth.js'; -import express, { Response } from 'express'; -import supertest from 'supertest'; -import { AuthInfo } from '../types.js'; -import { InvalidTokenError } from '../errors.js'; - -describe('Revocation Handler', () => { - // Mock client data - const validClient: OAuthClientInformationFull = { - client_id: 'valid-client', - client_secret: 'valid-secret', - redirect_uris: ['https://example.com/callback'] - }; - - // Mock client store - const mockClientStore: OAuthRegisteredClientsStore = { - async getClient(clientId: string): Promise { - if (clientId === 'valid-client') { - return validClient; - } - return undefined; - } - }; - - // Mock provider with revocation capability - const mockProviderWithRevocation: OAuthServerProvider = { - clientsStore: mockClientStore, - - async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise { - res.redirect('https://example.com/callback?code=mock_auth_code'); - }, - - async challengeForAuthorizationCode(): Promise { - return 'mock_challenge'; - }, - - async exchangeAuthorizationCode(): Promise { - return { - access_token: 'mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'mock_refresh_token' - }; - }, - - async exchangeRefreshToken(): Promise { - return { - access_token: 'new_mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'new_mock_refresh_token' - }; - }, - - async verifyAccessToken(token: string): Promise { - if (token === 'valid_token') { - return { - token, - clientId: 'valid-client', - scopes: ['read', 'write'], - expiresAt: Date.now() / 1000 + 3600 - }; - } - throw new InvalidTokenError('Token is invalid or expired'); - }, - - async revokeToken(_client: OAuthClientInformationFull, _request: OAuthTokenRevocationRequest): Promise { - // Success - do nothing in mock - } - }; - - // Mock provider without revocation capability - const mockProviderWithoutRevocation: OAuthServerProvider = { - clientsStore: mockClientStore, - - async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise { - res.redirect('https://example.com/callback?code=mock_auth_code'); - }, - - async challengeForAuthorizationCode(): Promise { - return 'mock_challenge'; - }, - - async exchangeAuthorizationCode(): Promise { - return { - access_token: 'mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'mock_refresh_token' - }; - }, - - async exchangeRefreshToken(): Promise { - return { - access_token: 'new_mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'new_mock_refresh_token' - }; - }, - - async verifyAccessToken(token: string): Promise { - if (token === 'valid_token') { - return { - token, - clientId: 'valid-client', - scopes: ['read', 'write'], - expiresAt: Date.now() / 1000 + 3600 - }; - } - throw new InvalidTokenError('Token is invalid or expired'); - } - // No revokeToken method - }; - - describe('Handler creation', () => { - it('throws error if provider does not support token revocation', () => { - const options: RevocationHandlerOptions = { provider: mockProviderWithoutRevocation }; - expect(() => revocationHandler(options)).toThrow('does not support revoking tokens'); - }); - - it('creates handler if provider supports token revocation', () => { - const options: RevocationHandlerOptions = { provider: mockProviderWithRevocation }; - expect(() => revocationHandler(options)).not.toThrow(); - }); - }); - - describe('Request handling', () => { - let app: express.Express; - let spyRevokeToken: jest.SpyInstance; - - beforeEach(() => { - // Setup express app with revocation handler - app = express(); - const options: RevocationHandlerOptions = { provider: mockProviderWithRevocation }; - app.use('/revoke', revocationHandler(options)); - - // Spy on the revokeToken method - spyRevokeToken = jest.spyOn(mockProviderWithRevocation, 'revokeToken'); - }); - - afterEach(() => { - spyRevokeToken.mockRestore(); - }); - - it('requires POST method', async () => { - const response = await supertest(app).get('/revoke').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - token: 'token_to_revoke' - }); - - expect(response.status).toBe(405); - expect(response.headers.allow).toBe('POST'); - expect(response.body).toEqual({ - error: 'method_not_allowed', - error_description: 'The method GET is not allowed for this endpoint' - }); - expect(spyRevokeToken).not.toHaveBeenCalled(); - }); - - it('requires token parameter', async () => { - const response = await supertest(app).post('/revoke').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret' - // Missing token - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_request'); - expect(spyRevokeToken).not.toHaveBeenCalled(); - }); - - it('authenticates client before revoking token', async () => { - const response = await supertest(app).post('/revoke').type('form').send({ - client_id: 'invalid-client', - client_secret: 'wrong-secret', - token: 'token_to_revoke' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_client'); - expect(spyRevokeToken).not.toHaveBeenCalled(); - }); - - it('successfully revokes token', async () => { - const response = await supertest(app).post('/revoke').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - token: 'token_to_revoke' - }); - - expect(response.status).toBe(200); - expect(response.body).toEqual({}); // Empty response on success - expect(spyRevokeToken).toHaveBeenCalledTimes(1); - expect(spyRevokeToken).toHaveBeenCalledWith(validClient, { - token: 'token_to_revoke' - }); - }); - - it('accepts optional token_type_hint', async () => { - const response = await supertest(app).post('/revoke').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - token: 'token_to_revoke', - token_type_hint: 'refresh_token' - }); - - expect(response.status).toBe(200); - expect(spyRevokeToken).toHaveBeenCalledWith(validClient, { - token: 'token_to_revoke', - token_type_hint: 'refresh_token' - }); - }); - - it('includes CORS headers in response', async () => { - const response = await supertest(app).post('/revoke').type('form').set('Origin', 'https://example.com').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - token: 'token_to_revoke' - }); - - expect(response.header['access-control-allow-origin']).toBe('*'); - }); - }); -}); diff --git a/typescript-sdk/src/server/auth/handlers/revoke.ts b/typescript-sdk/src/server/auth/handlers/revoke.ts deleted file mode 100644 index da7ef04..0000000 --- a/typescript-sdk/src/server/auth/handlers/revoke.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { OAuthServerProvider } from '../provider.js'; -import express, { RequestHandler } from 'express'; -import cors from 'cors'; -import { authenticateClient } from '../middleware/clientAuth.js'; -import { OAuthTokenRevocationRequestSchema } from '../../../shared/auth.js'; -import { rateLimit, Options as RateLimitOptions } from 'express-rate-limit'; -import { allowedMethods } from '../middleware/allowedMethods.js'; -import { InvalidRequestError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; - -export type RevocationHandlerOptions = { - provider: OAuthServerProvider; - /** - * Rate limiting configuration for the token revocation endpoint. - * Set to false to disable rate limiting for this endpoint. - */ - rateLimit?: Partial | false; -}; - -export function revocationHandler({ provider, rateLimit: rateLimitConfig }: RevocationHandlerOptions): RequestHandler { - if (!provider.revokeToken) { - throw new Error('Auth provider does not support revoking tokens'); - } - - // Nested router so we can configure middleware and restrict HTTP method - const router = express.Router(); - - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use(cors()); - - router.use(allowedMethods(['POST'])); - router.use(express.urlencoded({ extended: false })); - - // Apply rate limiting unless explicitly disabled - if (rateLimitConfig !== false) { - router.use( - rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 50, // 50 requests per windowMs - standardHeaders: true, - legacyHeaders: false, - message: new TooManyRequestsError('You have exceeded the rate limit for token revocation requests').toResponseObject(), - ...rateLimitConfig - }) - ); - } - - // Authenticate and extract client details - router.use(authenticateClient({ clientsStore: provider.clientsStore })); - - router.post('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - - try { - const parseResult = OAuthTokenRevocationRequestSchema.safeParse(req.body); - if (!parseResult.success) { - throw new InvalidRequestError(parseResult.error.message); - } - - const client = req.client; - if (!client) { - // This should never happen - throw new ServerError('Internal Server Error'); - } - - await provider.revokeToken!(client, parseResult.data); - res.status(200).json({}); - } catch (error) { - if (error instanceof OAuthError) { - const status = error instanceof ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }); - - return router; -} diff --git a/typescript-sdk/src/server/auth/handlers/token.test.ts b/typescript-sdk/src/server/auth/handlers/token.test.ts deleted file mode 100644 index e0338f0..0000000 --- a/typescript-sdk/src/server/auth/handlers/token.test.ts +++ /dev/null @@ -1,478 +0,0 @@ -import { tokenHandler, TokenHandlerOptions } from './token.js'; -import { OAuthServerProvider, AuthorizationParams } from '../provider.js'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../../shared/auth.js'; -import express, { Response } from 'express'; -import supertest from 'supertest'; -import * as pkceChallenge from 'pkce-challenge'; -import { InvalidGrantError, InvalidTokenError } from '../errors.js'; -import { AuthInfo } from '../types.js'; -import { ProxyOAuthServerProvider } from '../providers/proxyProvider.js'; - -// Mock pkce-challenge -jest.mock('pkce-challenge', () => ({ - verifyChallenge: jest.fn().mockImplementation(async (verifier, challenge) => { - return verifier === 'valid_verifier' && challenge === 'mock_challenge'; - }) -})); - -const mockTokens = { - access_token: 'mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'mock_refresh_token' -}; - -const mockTokensWithIdToken = { - ...mockTokens, - id_token: 'mock_id_token' -}; - -describe('Token Handler', () => { - // Mock client data - const validClient: OAuthClientInformationFull = { - client_id: 'valid-client', - client_secret: 'valid-secret', - redirect_uris: ['https://example.com/callback'] - }; - - // Mock client store - const mockClientStore: OAuthRegisteredClientsStore = { - async getClient(clientId: string): Promise { - if (clientId === 'valid-client') { - return validClient; - } - return undefined; - } - }; - - // Mock provider - let mockProvider: OAuthServerProvider; - let app: express.Express; - - beforeEach(() => { - // Create fresh mocks for each test - mockProvider = { - clientsStore: mockClientStore, - - async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise { - res.redirect('https://example.com/callback?code=mock_auth_code'); - }, - - async challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise { - if (authorizationCode === 'valid_code') { - return 'mock_challenge'; - } else if (authorizationCode === 'expired_code') { - throw new InvalidGrantError('The authorization code has expired'); - } - throw new InvalidGrantError('The authorization code is invalid'); - }, - - async exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise { - if (authorizationCode === 'valid_code') { - return mockTokens; - } - throw new InvalidGrantError('The authorization code is invalid or has expired'); - }, - - async exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[]): Promise { - if (refreshToken === 'valid_refresh_token') { - const response: OAuthTokens = { - access_token: 'new_mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'new_mock_refresh_token' - }; - - if (scopes) { - response.scope = scopes.join(' '); - } - - return response; - } - throw new InvalidGrantError('The refresh token is invalid or has expired'); - }, - - async verifyAccessToken(token: string): Promise { - if (token === 'valid_token') { - return { - token, - clientId: 'valid-client', - scopes: ['read', 'write'], - expiresAt: Date.now() / 1000 + 3600 - }; - } - throw new InvalidTokenError('Token is invalid or expired'); - }, - - async revokeToken(_client: OAuthClientInformationFull, _request: OAuthTokenRevocationRequest): Promise { - // Do nothing in mock - } - }; - - // Mock PKCE verification - (pkceChallenge.verifyChallenge as jest.Mock).mockImplementation(async (verifier: string, challenge: string) => { - return verifier === 'valid_verifier' && challenge === 'mock_challenge'; - }); - - // Setup express app with token handler - app = express(); - const options: TokenHandlerOptions = { provider: mockProvider }; - app.use('/token', tokenHandler(options)); - }); - - describe('Basic request validation', () => { - it('requires POST method', async () => { - const response = await supertest(app).get('/token').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code' - }); - - expect(response.status).toBe(405); - expect(response.headers.allow).toBe('POST'); - expect(response.body).toEqual({ - error: 'method_not_allowed', - error_description: 'The method GET is not allowed for this endpoint' - }); - }); - - it('requires grant_type parameter', async () => { - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret' - // Missing grant_type - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_request'); - }); - - it('rejects unsupported grant types', async () => { - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'password' // Unsupported grant type - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('unsupported_grant_type'); - }); - }); - - describe('Client authentication', () => { - it('requires valid client credentials', async () => { - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'invalid-client', - client_secret: 'wrong-secret', - grant_type: 'authorization_code' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_client'); - }); - - it('accepts valid client credentials', async () => { - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'valid_verifier' - }); - - expect(response.status).toBe(200); - }); - }); - - describe('Authorization code grant', () => { - it('requires code parameter', async () => { - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - // Missing code - code_verifier: 'valid_verifier' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_request'); - }); - - it('requires code_verifier parameter', async () => { - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code' - // Missing code_verifier - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_request'); - }); - - it('verifies code_verifier against challenge', async () => { - // Setup invalid verifier - (pkceChallenge.verifyChallenge as jest.Mock).mockResolvedValueOnce(false); - - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'invalid_verifier' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_grant'); - expect(response.body.error_description).toContain('code_verifier'); - }); - - it('rejects expired or invalid authorization codes', async () => { - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'expired_code', - code_verifier: 'valid_verifier' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_grant'); - }); - - it('returns tokens for valid code exchange', async () => { - const mockExchangeCode = jest.spyOn(mockProvider, 'exchangeAuthorizationCode'); - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - resource: 'https://api.example.com/resource', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'valid_verifier' - }); - - expect(response.status).toBe(200); - expect(response.body.access_token).toBe('mock_access_token'); - expect(response.body.token_type).toBe('bearer'); - expect(response.body.expires_in).toBe(3600); - expect(response.body.refresh_token).toBe('mock_refresh_token'); - expect(mockExchangeCode).toHaveBeenCalledWith( - validClient, - 'valid_code', - undefined, // code_verifier is undefined after PKCE validation - undefined, // redirect_uri - new URL('https://api.example.com/resource') // resource parameter - ); - }); - - it('returns id token in code exchange if provided', async () => { - mockProvider.exchangeAuthorizationCode = async ( - client: OAuthClientInformationFull, - authorizationCode: string - ): Promise => { - if (authorizationCode === 'valid_code') { - return mockTokensWithIdToken; - } - throw new InvalidGrantError('The authorization code is invalid or has expired'); - }; - - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'valid_verifier' - }); - - expect(response.status).toBe(200); - expect(response.body.id_token).toBe('mock_id_token'); - }); - - it('passes through code verifier when using proxy provider', async () => { - const originalFetch = global.fetch; - - try { - global.fetch = jest.fn().mockResolvedValue({ - ok: true, - json: () => Promise.resolve(mockTokens) - }); - - const proxyProvider = new ProxyOAuthServerProvider({ - endpoints: { - authorizationUrl: 'https://example.com/authorize', - tokenUrl: 'https://example.com/token' - }, - verifyAccessToken: async token => ({ - token, - clientId: 'valid-client', - scopes: ['read', 'write'], - expiresAt: Date.now() / 1000 + 3600 - }), - getClient: async clientId => (clientId === 'valid-client' ? validClient : undefined) - }); - - const proxyApp = express(); - const options: TokenHandlerOptions = { provider: proxyProvider }; - proxyApp.use('/token', tokenHandler(options)); - - const response = await supertest(proxyApp).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'any_verifier', - redirect_uri: 'https://example.com/callback' - }); - - expect(response.status).toBe(200); - expect(response.body.access_token).toBe('mock_access_token'); - - expect(global.fetch).toHaveBeenCalledWith( - 'https://example.com/token', - expect.objectContaining({ - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: expect.stringContaining('code_verifier=any_verifier') - }) - ); - } finally { - global.fetch = originalFetch; - } - }); - - it('passes through redirect_uri when using proxy provider', async () => { - const originalFetch = global.fetch; - - try { - global.fetch = jest.fn().mockResolvedValue({ - ok: true, - json: () => Promise.resolve(mockTokens) - }); - - const proxyProvider = new ProxyOAuthServerProvider({ - endpoints: { - authorizationUrl: 'https://example.com/authorize', - tokenUrl: 'https://example.com/token' - }, - verifyAccessToken: async token => ({ - token, - clientId: 'valid-client', - scopes: ['read', 'write'], - expiresAt: Date.now() / 1000 + 3600 - }), - getClient: async clientId => (clientId === 'valid-client' ? validClient : undefined) - }); - - const proxyApp = express(); - const options: TokenHandlerOptions = { provider: proxyProvider }; - proxyApp.use('/token', tokenHandler(options)); - - const redirectUri = 'https://example.com/callback'; - const response = await supertest(proxyApp).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'any_verifier', - redirect_uri: redirectUri - }); - - expect(response.status).toBe(200); - expect(response.body.access_token).toBe('mock_access_token'); - - expect(global.fetch).toHaveBeenCalledWith( - 'https://example.com/token', - expect.objectContaining({ - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: expect.stringContaining(`redirect_uri=${encodeURIComponent(redirectUri)}`) - }) - ); - } finally { - global.fetch = originalFetch; - } - }); - }); - - describe('Refresh token grant', () => { - it('requires refresh_token parameter', async () => { - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'refresh_token' - // Missing refresh_token - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_request'); - }); - - it('rejects invalid refresh tokens', async () => { - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'refresh_token', - refresh_token: 'invalid_refresh_token' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_grant'); - }); - - it('returns new tokens for valid refresh token', async () => { - const mockExchangeRefresh = jest.spyOn(mockProvider, 'exchangeRefreshToken'); - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - resource: 'https://api.example.com/resource', - grant_type: 'refresh_token', - refresh_token: 'valid_refresh_token' - }); - - expect(response.status).toBe(200); - expect(response.body.access_token).toBe('new_mock_access_token'); - expect(response.body.token_type).toBe('bearer'); - expect(response.body.expires_in).toBe(3600); - expect(response.body.refresh_token).toBe('new_mock_refresh_token'); - expect(mockExchangeRefresh).toHaveBeenCalledWith( - validClient, - 'valid_refresh_token', - undefined, // scopes - new URL('https://api.example.com/resource') // resource parameter - ); - }); - - it('respects requested scopes on refresh', async () => { - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'refresh_token', - refresh_token: 'valid_refresh_token', - scope: 'profile email' - }); - - expect(response.status).toBe(200); - expect(response.body.scope).toBe('profile email'); - }); - }); - - describe('CORS support', () => { - it('includes CORS headers in response', async () => { - const response = await supertest(app).post('/token').type('form').set('Origin', 'https://example.com').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'valid_verifier' - }); - - expect(response.header['access-control-allow-origin']).toBe('*'); - }); - }); -}); diff --git a/typescript-sdk/src/server/auth/handlers/token.ts b/typescript-sdk/src/server/auth/handlers/token.ts deleted file mode 100644 index c387ff7..0000000 --- a/typescript-sdk/src/server/auth/handlers/token.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { z } from 'zod'; -import express, { RequestHandler } from 'express'; -import { OAuthServerProvider } from '../provider.js'; -import cors from 'cors'; -import { verifyChallenge } from 'pkce-challenge'; -import { authenticateClient } from '../middleware/clientAuth.js'; -import { rateLimit, Options as RateLimitOptions } from 'express-rate-limit'; -import { allowedMethods } from '../middleware/allowedMethods.js'; -import { - InvalidRequestError, - InvalidGrantError, - UnsupportedGrantTypeError, - ServerError, - TooManyRequestsError, - OAuthError -} from '../errors.js'; - -export type TokenHandlerOptions = { - provider: OAuthServerProvider; - /** - * Rate limiting configuration for the token endpoint. - * Set to false to disable rate limiting for this endpoint. - */ - rateLimit?: Partial | false; -}; - -const TokenRequestSchema = z.object({ - grant_type: z.string() -}); - -const AuthorizationCodeGrantSchema = z.object({ - code: z.string(), - code_verifier: z.string(), - redirect_uri: z.string().optional(), - resource: z.string().url().optional() -}); - -const RefreshTokenGrantSchema = z.object({ - refresh_token: z.string(), - scope: z.string().optional(), - resource: z.string().url().optional() -}); - -export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler { - // Nested router so we can configure middleware and restrict HTTP method - const router = express.Router(); - - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use(cors()); - - router.use(allowedMethods(['POST'])); - router.use(express.urlencoded({ extended: false })); - - // Apply rate limiting unless explicitly disabled - if (rateLimitConfig !== false) { - router.use( - rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 50, // 50 requests per windowMs - standardHeaders: true, - legacyHeaders: false, - message: new TooManyRequestsError('You have exceeded the rate limit for token requests').toResponseObject(), - ...rateLimitConfig - }) - ); - } - - // Authenticate and extract client details - router.use(authenticateClient({ clientsStore: provider.clientsStore })); - - router.post('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - - try { - const parseResult = TokenRequestSchema.safeParse(req.body); - if (!parseResult.success) { - throw new InvalidRequestError(parseResult.error.message); - } - - const { grant_type } = parseResult.data; - - const client = req.client; - if (!client) { - // This should never happen - throw new ServerError('Internal Server Error'); - } - - switch (grant_type) { - case 'authorization_code': { - const parseResult = AuthorizationCodeGrantSchema.safeParse(req.body); - if (!parseResult.success) { - throw new InvalidRequestError(parseResult.error.message); - } - - const { code, code_verifier, redirect_uri, resource } = parseResult.data; - - const skipLocalPkceValidation = provider.skipLocalPkceValidation; - - // Perform local PKCE validation unless explicitly skipped - // (e.g. to validate code_verifier in upstream server) - if (!skipLocalPkceValidation) { - const codeChallenge = await provider.challengeForAuthorizationCode(client, code); - if (!(await verifyChallenge(code_verifier, codeChallenge))) { - throw new InvalidGrantError('code_verifier does not match the challenge'); - } - } - - // Passes the code_verifier to the provider if PKCE validation didn't occur locally - const tokens = await provider.exchangeAuthorizationCode( - client, - code, - skipLocalPkceValidation ? code_verifier : undefined, - redirect_uri, - resource ? new URL(resource) : undefined - ); - res.status(200).json(tokens); - break; - } - - case 'refresh_token': { - const parseResult = RefreshTokenGrantSchema.safeParse(req.body); - if (!parseResult.success) { - throw new InvalidRequestError(parseResult.error.message); - } - - const { refresh_token, scope, resource } = parseResult.data; - - const scopes = scope?.split(' '); - const tokens = await provider.exchangeRefreshToken( - client, - refresh_token, - scopes, - resource ? new URL(resource) : undefined - ); - res.status(200).json(tokens); - break; - } - - // Not supported right now - //case "client_credentials": - - default: - throw new UnsupportedGrantTypeError('The grant type is not supported by this authorization server.'); - } - } catch (error) { - if (error instanceof OAuthError) { - const status = error instanceof ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }); - - return router; -} diff --git a/typescript-sdk/src/server/auth/middleware/allowedMethods.test.ts b/typescript-sdk/src/server/auth/middleware/allowedMethods.test.ts deleted file mode 100644 index 1f30fea..0000000 --- a/typescript-sdk/src/server/auth/middleware/allowedMethods.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { allowedMethods } from './allowedMethods.js'; -import express, { Request, Response } from 'express'; -import request from 'supertest'; - -describe('allowedMethods', () => { - let app: express.Express; - - beforeEach(() => { - app = express(); - - // Set up a test router with a GET handler and 405 middleware - const router = express.Router(); - - router.get('/test', (req, res) => { - res.status(200).send('GET success'); - }); - - // Add method not allowed middleware for all other methods - router.all('/test', allowedMethods(['GET'])); - - app.use(router); - }); - - test('allows specified HTTP method', async () => { - const response = await request(app).get('/test'); - expect(response.status).toBe(200); - expect(response.text).toBe('GET success'); - }); - - test('returns 405 for unspecified HTTP methods', async () => { - const methods = ['post', 'put', 'delete', 'patch']; - - for (const method of methods) { - // @ts-expect-error - dynamic method call - const response = await request(app)[method]('/test'); - expect(response.status).toBe(405); - expect(response.body).toEqual({ - error: 'method_not_allowed', - error_description: `The method ${method.toUpperCase()} is not allowed for this endpoint` - }); - } - }); - - test('includes Allow header with specified methods', async () => { - const response = await request(app).post('/test'); - expect(response.headers.allow).toBe('GET'); - }); - - test('works with multiple allowed methods', async () => { - const multiMethodApp = express(); - const router = express.Router(); - - router.get('/multi', (req: Request, res: Response) => { - res.status(200).send('GET'); - }); - router.post('/multi', (req: Request, res: Response) => { - res.status(200).send('POST'); - }); - router.all('/multi', allowedMethods(['GET', 'POST'])); - - multiMethodApp.use(router); - - // Allowed methods should work - const getResponse = await request(multiMethodApp).get('/multi'); - expect(getResponse.status).toBe(200); - - const postResponse = await request(multiMethodApp).post('/multi'); - expect(postResponse.status).toBe(200); - - // Unallowed methods should return 405 - const putResponse = await request(multiMethodApp).put('/multi'); - expect(putResponse.status).toBe(405); - expect(putResponse.headers.allow).toBe('GET, POST'); - }); -}); diff --git a/typescript-sdk/src/server/auth/middleware/allowedMethods.ts b/typescript-sdk/src/server/auth/middleware/allowedMethods.ts deleted file mode 100644 index 74633aa..0000000 --- a/typescript-sdk/src/server/auth/middleware/allowedMethods.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { RequestHandler } from 'express'; -import { MethodNotAllowedError } from '../errors.js'; - -/** - * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. - * - * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) - * @returns Express middleware that returns a 405 error if method not in allowed list - */ -export function allowedMethods(allowedMethods: string[]): RequestHandler { - return (req, res, next) => { - if (allowedMethods.includes(req.method)) { - next(); - return; - } - - const error = new MethodNotAllowedError(`The method ${req.method} is not allowed for this endpoint`); - res.status(405).set('Allow', allowedMethods.join(', ')).json(error.toResponseObject()); - }; -} diff --git a/typescript-sdk/src/server/auth/middleware/bearerAuth.test.ts b/typescript-sdk/src/server/auth/middleware/bearerAuth.test.ts deleted file mode 100644 index 5790a0e..0000000 --- a/typescript-sdk/src/server/auth/middleware/bearerAuth.test.ts +++ /dev/null @@ -1,438 +0,0 @@ -import { Request, Response } from 'express'; -import { requireBearerAuth } from './bearerAuth.js'; -import { AuthInfo } from '../types.js'; -import { InsufficientScopeError, InvalidTokenError, CustomOAuthError, ServerError } from '../errors.js'; -import { OAuthTokenVerifier } from '../provider.js'; - -// Mock verifier -const mockVerifyAccessToken = jest.fn(); -const mockVerifier: OAuthTokenVerifier = { - verifyAccessToken: mockVerifyAccessToken -}; - -describe('requireBearerAuth middleware', () => { - let mockRequest: Partial; - let mockResponse: Partial; - let nextFunction: jest.Mock; - - beforeEach(() => { - mockRequest = { - headers: {} - }; - mockResponse = { - status: jest.fn().mockReturnThis(), - json: jest.fn(), - set: jest.fn().mockReturnThis() - }; - nextFunction = jest.fn(); - jest.spyOn(console, 'error').mockImplementation(() => {}); - }); - - afterEach(() => { - jest.clearAllMocks(); - }); - - it('should call next when token is valid', async () => { - const validAuthInfo: AuthInfo = { - token: 'valid-token', - clientId: 'client-123', - scopes: ['read', 'write'], - expiresAt: Math.floor(Date.now() / 1000) + 3600 // Token expires in an hour - }; - mockVerifyAccessToken.mockResolvedValue(validAuthInfo); - - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('valid-token'); - expect(mockRequest.auth).toEqual(validAuthInfo); - expect(nextFunction).toHaveBeenCalled(); - expect(mockResponse.status).not.toHaveBeenCalled(); - expect(mockResponse.json).not.toHaveBeenCalled(); - }); - - it.each([ - [100], // Token expired 100 seconds ago - [0] // Token expires at the same time as now - ])('should reject expired tokens (expired %s seconds ago)', async (expiredSecondsAgo: number) => { - const expiresAt = Math.floor(Date.now() / 1000) - expiredSecondsAgo; - const expiredAuthInfo: AuthInfo = { - token: 'expired-token', - clientId: 'client-123', - scopes: ['read', 'write'], - expiresAt - }; - mockVerifyAccessToken.mockResolvedValue(expiredAuthInfo); - - mockRequest.headers = { - authorization: 'Bearer expired-token' - }; - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('expired-token'); - expect(mockResponse.status).toHaveBeenCalledWith(401); - expect(mockResponse.set).toHaveBeenCalledWith('WWW-Authenticate', expect.stringContaining('Bearer error="invalid_token"')); - expect(mockResponse.json).toHaveBeenCalledWith( - expect.objectContaining({ error: 'invalid_token', error_description: 'Token has expired' }) - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it.each([ - [undefined], // Token has no expiration time - [NaN] // Token has no expiration time - ])('should reject tokens with no expiration time (expiresAt: %s)', async (expiresAt: number | undefined) => { - const noExpirationAuthInfo: AuthInfo = { - token: 'no-expiration-token', - clientId: 'client-123', - scopes: ['read', 'write'], - expiresAt - }; - mockVerifyAccessToken.mockResolvedValue(noExpirationAuthInfo); - - mockRequest.headers = { - authorization: 'Bearer expired-token' - }; - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('expired-token'); - expect(mockResponse.status).toHaveBeenCalledWith(401); - expect(mockResponse.set).toHaveBeenCalledWith('WWW-Authenticate', expect.stringContaining('Bearer error="invalid_token"')); - expect(mockResponse.json).toHaveBeenCalledWith( - expect.objectContaining({ error: 'invalid_token', error_description: 'Token has no expiration time' }) - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should accept non-expired tokens', async () => { - const nonExpiredAuthInfo: AuthInfo = { - token: 'valid-token', - clientId: 'client-123', - scopes: ['read', 'write'], - expiresAt: Math.floor(Date.now() / 1000) + 3600 // Token expires in an hour - }; - mockVerifyAccessToken.mockResolvedValue(nonExpiredAuthInfo); - - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('valid-token'); - expect(mockRequest.auth).toEqual(nonExpiredAuthInfo); - expect(nextFunction).toHaveBeenCalled(); - expect(mockResponse.status).not.toHaveBeenCalled(); - expect(mockResponse.json).not.toHaveBeenCalled(); - }); - - it('should require specific scopes when configured', async () => { - const authInfo: AuthInfo = { - token: 'valid-token', - clientId: 'client-123', - scopes: ['read'] - }; - mockVerifyAccessToken.mockResolvedValue(authInfo); - - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - const middleware = requireBearerAuth({ - verifier: mockVerifier, - requiredScopes: ['read', 'write'] - }); - - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('valid-token'); - expect(mockResponse.status).toHaveBeenCalledWith(403); - expect(mockResponse.set).toHaveBeenCalledWith('WWW-Authenticate', expect.stringContaining('Bearer error="insufficient_scope"')); - expect(mockResponse.json).toHaveBeenCalledWith( - expect.objectContaining({ error: 'insufficient_scope', error_description: 'Insufficient scope' }) - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should accept token with all required scopes', async () => { - const authInfo: AuthInfo = { - token: 'valid-token', - clientId: 'client-123', - scopes: ['read', 'write', 'admin'], - expiresAt: Math.floor(Date.now() / 1000) + 3600 // Token expires in an hour - }; - mockVerifyAccessToken.mockResolvedValue(authInfo); - - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - const middleware = requireBearerAuth({ - verifier: mockVerifier, - requiredScopes: ['read', 'write'] - }); - - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('valid-token'); - expect(mockRequest.auth).toEqual(authInfo); - expect(nextFunction).toHaveBeenCalled(); - expect(mockResponse.status).not.toHaveBeenCalled(); - expect(mockResponse.json).not.toHaveBeenCalled(); - }); - - it('should return 401 when no Authorization header is present', async () => { - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).not.toHaveBeenCalled(); - expect(mockResponse.status).toHaveBeenCalledWith(401); - expect(mockResponse.set).toHaveBeenCalledWith('WWW-Authenticate', expect.stringContaining('Bearer error="invalid_token"')); - expect(mockResponse.json).toHaveBeenCalledWith( - expect.objectContaining({ error: 'invalid_token', error_description: 'Missing Authorization header' }) - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should return 401 when Authorization header format is invalid', async () => { - mockRequest.headers = { - authorization: 'InvalidFormat' - }; - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).not.toHaveBeenCalled(); - expect(mockResponse.status).toHaveBeenCalledWith(401); - expect(mockResponse.set).toHaveBeenCalledWith('WWW-Authenticate', expect.stringContaining('Bearer error="invalid_token"')); - expect(mockResponse.json).toHaveBeenCalledWith( - expect.objectContaining({ - error: 'invalid_token', - error_description: "Invalid Authorization header format, expected 'Bearer TOKEN'" - }) - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should return 401 when token verification fails with InvalidTokenError', async () => { - mockRequest.headers = { - authorization: 'Bearer invalid-token' - }; - - mockVerifyAccessToken.mockRejectedValue(new InvalidTokenError('Token expired')); - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('invalid-token'); - expect(mockResponse.status).toHaveBeenCalledWith(401); - expect(mockResponse.set).toHaveBeenCalledWith('WWW-Authenticate', expect.stringContaining('Bearer error="invalid_token"')); - expect(mockResponse.json).toHaveBeenCalledWith( - expect.objectContaining({ error: 'invalid_token', error_description: 'Token expired' }) - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should return 403 when access token has insufficient scopes', async () => { - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - mockVerifyAccessToken.mockRejectedValue(new InsufficientScopeError('Required scopes: read, write')); - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('valid-token'); - expect(mockResponse.status).toHaveBeenCalledWith(403); - expect(mockResponse.set).toHaveBeenCalledWith('WWW-Authenticate', expect.stringContaining('Bearer error="insufficient_scope"')); - expect(mockResponse.json).toHaveBeenCalledWith( - expect.objectContaining({ error: 'insufficient_scope', error_description: 'Required scopes: read, write' }) - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should return 500 when a ServerError occurs', async () => { - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - mockVerifyAccessToken.mockRejectedValue(new ServerError('Internal server issue')); - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('valid-token'); - expect(mockResponse.status).toHaveBeenCalledWith(500); - expect(mockResponse.json).toHaveBeenCalledWith( - expect.objectContaining({ error: 'server_error', error_description: 'Internal server issue' }) - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should return 400 for generic OAuthError', async () => { - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - mockVerifyAccessToken.mockRejectedValue(new CustomOAuthError('custom_error', 'Some OAuth error')); - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('valid-token'); - expect(mockResponse.status).toHaveBeenCalledWith(400); - expect(mockResponse.json).toHaveBeenCalledWith( - expect.objectContaining({ error: 'custom_error', error_description: 'Some OAuth error' }) - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should return 500 when unexpected error occurs', async () => { - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - mockVerifyAccessToken.mockRejectedValue(new Error('Unexpected error')); - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith('valid-token'); - expect(mockResponse.status).toHaveBeenCalledWith(500); - expect(mockResponse.json).toHaveBeenCalledWith( - expect.objectContaining({ error: 'server_error', error_description: 'Internal Server Error' }) - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - describe('with resourceMetadataUrl', () => { - const resourceMetadataUrl = 'https://api.example.com/.well-known/oauth-protected-resource'; - - it('should include resource_metadata in WWW-Authenticate header for 401 responses', async () => { - mockRequest.headers = {}; - - const middleware = requireBearerAuth({ verifier: mockVerifier, resourceMetadataUrl }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockResponse.status).toHaveBeenCalledWith(401); - expect(mockResponse.set).toHaveBeenCalledWith( - 'WWW-Authenticate', - `Bearer error="invalid_token", error_description="Missing Authorization header", resource_metadata="${resourceMetadataUrl}"` - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should include resource_metadata in WWW-Authenticate header when token verification fails', async () => { - mockRequest.headers = { - authorization: 'Bearer invalid-token' - }; - - mockVerifyAccessToken.mockRejectedValue(new InvalidTokenError('Token expired')); - - const middleware = requireBearerAuth({ verifier: mockVerifier, resourceMetadataUrl }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockResponse.status).toHaveBeenCalledWith(401); - expect(mockResponse.set).toHaveBeenCalledWith( - 'WWW-Authenticate', - `Bearer error="invalid_token", error_description="Token expired", resource_metadata="${resourceMetadataUrl}"` - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should include resource_metadata in WWW-Authenticate header for insufficient scope errors', async () => { - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - mockVerifyAccessToken.mockRejectedValue(new InsufficientScopeError('Required scopes: admin')); - - const middleware = requireBearerAuth({ verifier: mockVerifier, resourceMetadataUrl }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockResponse.status).toHaveBeenCalledWith(403); - expect(mockResponse.set).toHaveBeenCalledWith( - 'WWW-Authenticate', - `Bearer error="insufficient_scope", error_description="Required scopes: admin", resource_metadata="${resourceMetadataUrl}"` - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should include resource_metadata when token is expired', async () => { - const expiredAuthInfo: AuthInfo = { - token: 'expired-token', - clientId: 'client-123', - scopes: ['read', 'write'], - expiresAt: Math.floor(Date.now() / 1000) - 100 - }; - mockVerifyAccessToken.mockResolvedValue(expiredAuthInfo); - - mockRequest.headers = { - authorization: 'Bearer expired-token' - }; - - const middleware = requireBearerAuth({ verifier: mockVerifier, resourceMetadataUrl }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockResponse.status).toHaveBeenCalledWith(401); - expect(mockResponse.set).toHaveBeenCalledWith( - 'WWW-Authenticate', - `Bearer error="invalid_token", error_description="Token has expired", resource_metadata="${resourceMetadataUrl}"` - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should include resource_metadata when scope check fails', async () => { - const authInfo: AuthInfo = { - token: 'valid-token', - clientId: 'client-123', - scopes: ['read'] - }; - mockVerifyAccessToken.mockResolvedValue(authInfo); - - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - const middleware = requireBearerAuth({ - verifier: mockVerifier, - requiredScopes: ['read', 'write'], - resourceMetadataUrl - }); - - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockResponse.status).toHaveBeenCalledWith(403); - expect(mockResponse.set).toHaveBeenCalledWith( - 'WWW-Authenticate', - `Bearer error="insufficient_scope", error_description="Insufficient scope", resource_metadata="${resourceMetadataUrl}"` - ); - expect(nextFunction).not.toHaveBeenCalled(); - }); - - it('should not affect server errors (no WWW-Authenticate header)', async () => { - mockRequest.headers = { - authorization: 'Bearer valid-token' - }; - - mockVerifyAccessToken.mockRejectedValue(new ServerError('Internal server issue')); - - const middleware = requireBearerAuth({ verifier: mockVerifier, resourceMetadataUrl }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockResponse.status).toHaveBeenCalledWith(500); - expect(mockResponse.set).not.toHaveBeenCalledWith('WWW-Authenticate', expect.anything()); - expect(nextFunction).not.toHaveBeenCalled(); - }); - }); -}); diff --git a/typescript-sdk/src/server/auth/middleware/bearerAuth.ts b/typescript-sdk/src/server/auth/middleware/bearerAuth.ts deleted file mode 100644 index 363fd7a..0000000 --- a/typescript-sdk/src/server/auth/middleware/bearerAuth.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { RequestHandler } from 'express'; -import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from '../errors.js'; -import { OAuthTokenVerifier } from '../provider.js'; -import { AuthInfo } from '../types.js'; - -export type BearerAuthMiddlewareOptions = { - /** - * A provider used to verify tokens. - */ - verifier: OAuthTokenVerifier; - - /** - * Optional scopes that the token must have. - */ - requiredScopes?: string[]; - - /** - * Optional resource metadata URL to include in WWW-Authenticate header. - */ - resourceMetadataUrl?: string; -}; - -declare module 'express-serve-static-core' { - interface Request { - /** - * Information about the validated access token, if the `requireBearerAuth` middleware was used. - */ - auth?: AuthInfo; - } -} - -/** - * Middleware that requires a valid Bearer token in the Authorization header. - * - * This will validate the token with the auth provider and add the resulting auth info to the request object. - * - * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header - * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. - */ -export function requireBearerAuth({ verifier, requiredScopes = [], resourceMetadataUrl }: BearerAuthMiddlewareOptions): RequestHandler { - return async (req, res, next) => { - try { - const authHeader = req.headers.authorization; - if (!authHeader) { - throw new InvalidTokenError('Missing Authorization header'); - } - - const [type, token] = authHeader.split(' '); - if (type.toLowerCase() !== 'bearer' || !token) { - throw new InvalidTokenError("Invalid Authorization header format, expected 'Bearer TOKEN'"); - } - - const authInfo = await verifier.verifyAccessToken(token); - - // Check if token has the required scopes (if any) - if (requiredScopes.length > 0) { - const hasAllScopes = requiredScopes.every(scope => authInfo.scopes.includes(scope)); - - if (!hasAllScopes) { - throw new InsufficientScopeError('Insufficient scope'); - } - } - - // Check if the token is set to expire or if it is expired - if (typeof authInfo.expiresAt !== 'number' || isNaN(authInfo.expiresAt)) { - throw new InvalidTokenError('Token has no expiration time'); - } else if (authInfo.expiresAt < Date.now() / 1000) { - throw new InvalidTokenError('Token has expired'); - } - - req.auth = authInfo; - next(); - } catch (error) { - if (error instanceof InvalidTokenError) { - const wwwAuthValue = resourceMetadataUrl - ? `Bearer error="${error.errorCode}", error_description="${error.message}", resource_metadata="${resourceMetadataUrl}"` - : `Bearer error="${error.errorCode}", error_description="${error.message}"`; - res.set('WWW-Authenticate', wwwAuthValue); - res.status(401).json(error.toResponseObject()); - } else if (error instanceof InsufficientScopeError) { - const wwwAuthValue = resourceMetadataUrl - ? `Bearer error="${error.errorCode}", error_description="${error.message}", resource_metadata="${resourceMetadataUrl}"` - : `Bearer error="${error.errorCode}", error_description="${error.message}"`; - res.set('WWW-Authenticate', wwwAuthValue); - res.status(403).json(error.toResponseObject()); - } else if (error instanceof ServerError) { - res.status(500).json(error.toResponseObject()); - } else if (error instanceof OAuthError) { - res.status(400).json(error.toResponseObject()); - } else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }; -} diff --git a/typescript-sdk/src/server/auth/middleware/clientAuth.test.ts b/typescript-sdk/src/server/auth/middleware/clientAuth.test.ts deleted file mode 100644 index 5ad6f30..0000000 --- a/typescript-sdk/src/server/auth/middleware/clientAuth.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { authenticateClient, ClientAuthenticationMiddlewareOptions } from './clientAuth.js'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { OAuthClientInformationFull } from '../../../shared/auth.js'; -import express from 'express'; -import supertest from 'supertest'; - -describe('clientAuth middleware', () => { - // Mock client store - const mockClientStore: OAuthRegisteredClientsStore = { - async getClient(clientId: string): Promise { - if (clientId === 'valid-client') { - return { - client_id: 'valid-client', - client_secret: 'valid-secret', - redirect_uris: ['https://example.com/callback'] - }; - } else if (clientId === 'expired-client') { - // Client with no secret - return { - client_id: 'expired-client', - redirect_uris: ['https://example.com/callback'] - }; - } else if (clientId === 'client-with-expired-secret') { - // Client with an expired secret - return { - client_id: 'client-with-expired-secret', - client_secret: 'expired-secret', - client_secret_expires_at: Math.floor(Date.now() / 1000) - 3600, // Expired 1 hour ago - redirect_uris: ['https://example.com/callback'] - }; - } - return undefined; - } - }; - - // Setup Express app with middleware - let app: express.Express; - let options: ClientAuthenticationMiddlewareOptions; - - beforeEach(() => { - app = express(); - app.use(express.json()); - - options = { - clientsStore: mockClientStore - }; - - // Setup route with client auth - app.post('/protected', authenticateClient(options), (req, res) => { - res.status(200).json({ success: true, client: req.client }); - }); - }); - - it('authenticates valid client credentials', async () => { - const response = await supertest(app).post('/protected').send({ - client_id: 'valid-client', - client_secret: 'valid-secret' - }); - - expect(response.status).toBe(200); - expect(response.body.success).toBe(true); - expect(response.body.client.client_id).toBe('valid-client'); - }); - - it('rejects invalid client_id', async () => { - const response = await supertest(app).post('/protected').send({ - client_id: 'non-existent-client', - client_secret: 'some-secret' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_client'); - expect(response.body.error_description).toBe('Invalid client_id'); - }); - - it('rejects invalid client_secret', async () => { - const response = await supertest(app).post('/protected').send({ - client_id: 'valid-client', - client_secret: 'wrong-secret' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_client'); - expect(response.body.error_description).toBe('Invalid client_secret'); - }); - - it('rejects missing client_id', async () => { - const response = await supertest(app).post('/protected').send({ - client_secret: 'valid-secret' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_request'); - }); - - it('allows missing client_secret if client has none', async () => { - const response = await supertest(app).post('/protected').send({ - client_id: 'expired-client' - }); - - // Since the client has no secret, this should pass without providing one - expect(response.status).toBe(200); - }); - - it('rejects request when client secret has expired', async () => { - const response = await supertest(app).post('/protected').send({ - client_id: 'client-with-expired-secret', - client_secret: 'expired-secret' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_client'); - expect(response.body.error_description).toBe('Client secret has expired'); - }); - - it('handles malformed request body', async () => { - const response = await supertest(app).post('/protected').send('not-json-format'); - - expect(response.status).toBe(400); - }); - - // Testing request with extra fields to ensure they're ignored - it('ignores extra fields in request', async () => { - const response = await supertest(app).post('/protected').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - extra_field: 'should be ignored' - }); - - expect(response.status).toBe(200); - }); -}); diff --git a/typescript-sdk/src/server/auth/middleware/clientAuth.ts b/typescript-sdk/src/server/auth/middleware/clientAuth.ts deleted file mode 100644 index 9969b87..0000000 --- a/typescript-sdk/src/server/auth/middleware/clientAuth.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { z } from 'zod'; -import { RequestHandler } from 'express'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { OAuthClientInformationFull } from '../../../shared/auth.js'; -import { InvalidRequestError, InvalidClientError, ServerError, OAuthError } from '../errors.js'; - -export type ClientAuthenticationMiddlewareOptions = { - /** - * A store used to read information about registered OAuth clients. - */ - clientsStore: OAuthRegisteredClientsStore; -}; - -const ClientAuthenticatedRequestSchema = z.object({ - client_id: z.string(), - client_secret: z.string().optional() -}); - -declare module 'express-serve-static-core' { - interface Request { - /** - * The authenticated client for this request, if the `authenticateClient` middleware was used. - */ - client?: OAuthClientInformationFull; - } -} - -export function authenticateClient({ clientsStore }: ClientAuthenticationMiddlewareOptions): RequestHandler { - return async (req, res, next) => { - try { - const result = ClientAuthenticatedRequestSchema.safeParse(req.body); - if (!result.success) { - throw new InvalidRequestError(String(result.error)); - } - - const { client_id, client_secret } = result.data; - const client = await clientsStore.getClient(client_id); - if (!client) { - throw new InvalidClientError('Invalid client_id'); - } - - // If client has a secret, validate it - if (client.client_secret) { - // Check if client_secret is required but not provided - if (!client_secret) { - throw new InvalidClientError('Client secret is required'); - } - - // Check if client_secret matches - if (client.client_secret !== client_secret) { - throw new InvalidClientError('Invalid client_secret'); - } - - // Check if client_secret has expired - if (client.client_secret_expires_at && client.client_secret_expires_at < Math.floor(Date.now() / 1000)) { - throw new InvalidClientError('Client secret has expired'); - } - } - - req.client = client; - next(); - } catch (error) { - if (error instanceof OAuthError) { - const status = error instanceof ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }; -} diff --git a/typescript-sdk/src/server/auth/provider.ts b/typescript-sdk/src/server/auth/provider.ts deleted file mode 100644 index cf1c306..0000000 --- a/typescript-sdk/src/server/auth/provider.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { Response } from 'express'; -import { OAuthRegisteredClientsStore } from './clients.js'; -import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../shared/auth.js'; -import { AuthInfo } from './types.js'; - -export type AuthorizationParams = { - state?: string; - scopes?: string[]; - codeChallenge: string; - redirectUri: string; - resource?: URL; -}; - -/** - * Implements an end-to-end OAuth server. - */ -export interface OAuthServerProvider { - /** - * A store used to read information about registered OAuth clients. - */ - get clientsStore(): OAuthRegisteredClientsStore; - - /** - * Begins the authorization flow, which can either be implemented by this server itself or via redirection to a separate authorization server. - * - * This server must eventually issue a redirect with an authorization response or an error response to the given redirect URI. Per OAuth 2.1: - * - In the successful case, the redirect MUST include the `code` and `state` (if present) query parameters. - * - In the error case, the redirect MUST include the `error` query parameter, and MAY include an optional `error_description` query parameter. - */ - authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; - - /** - * Returns the `codeChallenge` that was used when the indicated authorization began. - */ - challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; - - /** - * Exchanges an authorization code for an access token. - */ - exchangeAuthorizationCode( - client: OAuthClientInformationFull, - authorizationCode: string, - codeVerifier?: string, - redirectUri?: string, - resource?: URL - ): Promise; - - /** - * Exchanges a refresh token for an access token. - */ - exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; - - /** - * Verifies an access token and returns information about it. - */ - verifyAccessToken(token: string): Promise; - - /** - * Revokes an access or refresh token. If unimplemented, token revocation is not supported (not recommended). - * - * If the given token is invalid or already revoked, this method should do nothing. - */ - revokeToken?(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise; - - /** - * Whether to skip local PKCE validation. - * - * If true, the server will not perform PKCE validation locally and will pass the code_verifier to the upstream server. - * - * NOTE: This should only be true if the upstream server is performing the actual PKCE validation. - */ - skipLocalPkceValidation?: boolean; -} - -/** - * Slim implementation useful for token verification - */ -export interface OAuthTokenVerifier { - /** - * Verifies an access token and returns information about it. - */ - verifyAccessToken(token: string): Promise; -} diff --git a/typescript-sdk/src/server/auth/providers/proxyProvider.test.ts b/typescript-sdk/src/server/auth/providers/proxyProvider.test.ts deleted file mode 100644 index 97069ca..0000000 --- a/typescript-sdk/src/server/auth/providers/proxyProvider.test.ts +++ /dev/null @@ -1,343 +0,0 @@ -import { Response } from 'express'; -import { ProxyOAuthServerProvider, ProxyOptions } from './proxyProvider.js'; -import { AuthInfo } from '../types.js'; -import { OAuthClientInformationFull, OAuthTokens } from '../../../shared/auth.js'; -import { ServerError } from '../errors.js'; -import { InvalidTokenError } from '../errors.js'; -import { InsufficientScopeError } from '../errors.js'; - -describe('Proxy OAuth Server Provider', () => { - // Mock client data - const validClient: OAuthClientInformationFull = { - client_id: 'test-client', - client_secret: 'test-secret', - redirect_uris: ['https://example.com/callback'] - }; - - // Mock response object - const mockResponse = { - redirect: jest.fn() - } as unknown as Response; - - // Mock provider functions - const mockVerifyToken = jest.fn(); - const mockGetClient = jest.fn(); - - // Base provider options - const baseOptions: ProxyOptions = { - endpoints: { - authorizationUrl: 'https://auth.example.com/authorize', - tokenUrl: 'https://auth.example.com/token', - revocationUrl: 'https://auth.example.com/revoke', - registrationUrl: 'https://auth.example.com/register' - }, - verifyAccessToken: mockVerifyToken, - getClient: mockGetClient - }; - - let provider: ProxyOAuthServerProvider; - let originalFetch: typeof global.fetch; - - beforeEach(() => { - provider = new ProxyOAuthServerProvider(baseOptions); - originalFetch = global.fetch; - global.fetch = jest.fn(); - - // Setup mock implementations - mockVerifyToken.mockImplementation(async (token: string) => { - if (token === 'valid-token') { - return { - token, - clientId: 'test-client', - scopes: ['read', 'write'], - expiresAt: Date.now() / 1000 + 3600 - } as AuthInfo; - } - throw new InvalidTokenError('Invalid token'); - }); - - mockGetClient.mockImplementation(async (clientId: string) => { - if (clientId === 'test-client') { - return validClient; - } - return undefined; - }); - }); - - // Add helper function for failed responses - const mockFailedResponse = () => { - (global.fetch as jest.Mock).mockImplementation(() => - Promise.resolve({ - ok: false, - status: 400 - }) - ); - }; - - afterEach(() => { - global.fetch = originalFetch; - jest.clearAllMocks(); - }); - - describe('authorization', () => { - it('redirects to authorization endpoint with correct parameters', async () => { - await provider.authorize( - validClient, - { - redirectUri: 'https://example.com/callback', - codeChallenge: 'test-challenge', - state: 'test-state', - scopes: ['read', 'write'], - resource: new URL('https://api.example.com/resource') - }, - mockResponse - ); - - const expectedUrl = new URL('https://auth.example.com/authorize'); - expectedUrl.searchParams.set('client_id', 'test-client'); - expectedUrl.searchParams.set('response_type', 'code'); - expectedUrl.searchParams.set('redirect_uri', 'https://example.com/callback'); - expectedUrl.searchParams.set('code_challenge', 'test-challenge'); - expectedUrl.searchParams.set('code_challenge_method', 'S256'); - expectedUrl.searchParams.set('state', 'test-state'); - expectedUrl.searchParams.set('scope', 'read write'); - expectedUrl.searchParams.set('resource', 'https://api.example.com/resource'); - - expect(mockResponse.redirect).toHaveBeenCalledWith(expectedUrl.toString()); - }); - }); - - describe('token exchange', () => { - const mockTokenResponse: OAuthTokens = { - access_token: 'new-access-token', - token_type: 'Bearer', - expires_in: 3600, - refresh_token: 'new-refresh-token' - }; - - beforeEach(() => { - (global.fetch as jest.Mock).mockImplementation(() => - Promise.resolve({ - ok: true, - json: () => Promise.resolve(mockTokenResponse) - }) - ); - }); - - it('exchanges authorization code for tokens', async () => { - const tokens = await provider.exchangeAuthorizationCode(validClient, 'test-code', 'test-verifier'); - - expect(global.fetch).toHaveBeenCalledWith( - 'https://auth.example.com/token', - expect.objectContaining({ - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: expect.stringContaining('grant_type=authorization_code') - }) - ); - expect(tokens).toEqual(mockTokenResponse); - }); - - it('includes redirect_uri in token request when provided', async () => { - const redirectUri = 'https://example.com/callback'; - const tokens = await provider.exchangeAuthorizationCode(validClient, 'test-code', 'test-verifier', redirectUri); - - expect(global.fetch).toHaveBeenCalledWith( - 'https://auth.example.com/token', - expect.objectContaining({ - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: expect.stringContaining(`redirect_uri=${encodeURIComponent(redirectUri)}`) - }) - ); - expect(tokens).toEqual(mockTokenResponse); - }); - - it('includes resource parameter in authorization code exchange', async () => { - const tokens = await provider.exchangeAuthorizationCode( - validClient, - 'test-code', - 'test-verifier', - 'https://example.com/callback', - new URL('https://api.example.com/resource') - ); - - expect(global.fetch).toHaveBeenCalledWith( - 'https://auth.example.com/token', - expect.objectContaining({ - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: expect.stringContaining('resource=' + encodeURIComponent('https://api.example.com/resource')) - }) - ); - expect(tokens).toEqual(mockTokenResponse); - }); - - it('handles authorization code exchange without resource parameter', async () => { - const tokens = await provider.exchangeAuthorizationCode(validClient, 'test-code', 'test-verifier'); - - const fetchCall = (global.fetch as jest.Mock).mock.calls[0]; - const body = fetchCall[1].body as string; - expect(body).not.toContain('resource='); - expect(tokens).toEqual(mockTokenResponse); - }); - - it('exchanges refresh token for new tokens', async () => { - const tokens = await provider.exchangeRefreshToken(validClient, 'test-refresh-token', ['read', 'write']); - - expect(global.fetch).toHaveBeenCalledWith( - 'https://auth.example.com/token', - expect.objectContaining({ - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: expect.stringContaining('grant_type=refresh_token') - }) - ); - expect(tokens).toEqual(mockTokenResponse); - }); - - it('includes resource parameter in refresh token exchange', async () => { - const tokens = await provider.exchangeRefreshToken( - validClient, - 'test-refresh-token', - ['read', 'write'], - new URL('https://api.example.com/resource') - ); - - expect(global.fetch).toHaveBeenCalledWith( - 'https://auth.example.com/token', - expect.objectContaining({ - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: expect.stringContaining('resource=' + encodeURIComponent('https://api.example.com/resource')) - }) - ); - expect(tokens).toEqual(mockTokenResponse); - }); - }); - - describe('client registration', () => { - it('registers new client', async () => { - const newClient: OAuthClientInformationFull = { - client_id: 'new-client', - redirect_uris: ['https://new-client.com/callback'] - }; - - (global.fetch as jest.Mock).mockImplementation(() => - Promise.resolve({ - ok: true, - json: () => Promise.resolve(newClient) - }) - ); - - const result = await provider.clientsStore.registerClient!(newClient); - - expect(global.fetch).toHaveBeenCalledWith( - 'https://auth.example.com/register', - expect.objectContaining({ - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(newClient) - }) - ); - expect(result).toEqual(newClient); - }); - - it('handles registration failure', async () => { - mockFailedResponse(); - const newClient: OAuthClientInformationFull = { - client_id: 'new-client', - redirect_uris: ['https://new-client.com/callback'] - }; - - await expect(provider.clientsStore.registerClient!(newClient)).rejects.toThrow(ServerError); - }); - }); - - describe('token revocation', () => { - it('revokes token', async () => { - (global.fetch as jest.Mock).mockImplementation(() => - Promise.resolve({ - ok: true - }) - ); - - await provider.revokeToken!(validClient, { - token: 'token-to-revoke', - token_type_hint: 'access_token' - }); - - expect(global.fetch).toHaveBeenCalledWith( - 'https://auth.example.com/revoke', - expect.objectContaining({ - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: expect.stringContaining('token=token-to-revoke') - }) - ); - }); - - it('handles revocation failure', async () => { - mockFailedResponse(); - await expect( - provider.revokeToken!(validClient, { - token: 'invalid-token' - }) - ).rejects.toThrow(ServerError); - }); - }); - - describe('token verification', () => { - it('verifies valid token', async () => { - const validAuthInfo: AuthInfo = { - token: 'valid-token', - clientId: 'test-client', - scopes: ['read', 'write'], - expiresAt: Date.now() / 1000 + 3600 - }; - mockVerifyToken.mockResolvedValue(validAuthInfo); - - const authInfo = await provider.verifyAccessToken('valid-token'); - expect(authInfo).toEqual(validAuthInfo); - expect(mockVerifyToken).toHaveBeenCalledWith('valid-token'); - }); - - it('passes through InvalidTokenError', async () => { - const error = new InvalidTokenError('Token expired'); - mockVerifyToken.mockRejectedValue(error); - - await expect(provider.verifyAccessToken('invalid-token')).rejects.toBe(error); - expect(mockVerifyToken).toHaveBeenCalledWith('invalid-token'); - }); - - it('passes through InsufficientScopeError', async () => { - const error = new InsufficientScopeError('Required scopes: read, write'); - mockVerifyToken.mockRejectedValue(error); - - await expect(provider.verifyAccessToken('token-with-insufficient-scope')).rejects.toBe(error); - expect(mockVerifyToken).toHaveBeenCalledWith('token-with-insufficient-scope'); - }); - - it('passes through unexpected errors', async () => { - const error = new Error('Unexpected error'); - mockVerifyToken.mockRejectedValue(error); - - await expect(provider.verifyAccessToken('valid-token')).rejects.toBe(error); - expect(mockVerifyToken).toHaveBeenCalledWith('valid-token'); - }); - }); -}); diff --git a/typescript-sdk/src/server/auth/providers/proxyProvider.ts b/typescript-sdk/src/server/auth/providers/proxyProvider.ts deleted file mode 100644 index 32f2564..0000000 --- a/typescript-sdk/src/server/auth/providers/proxyProvider.ts +++ /dev/null @@ -1,234 +0,0 @@ -import { Response } from 'express'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { - OAuthClientInformationFull, - OAuthClientInformationFullSchema, - OAuthTokenRevocationRequest, - OAuthTokens, - OAuthTokensSchema -} from '../../../shared/auth.js'; -import { AuthInfo } from '../types.js'; -import { AuthorizationParams, OAuthServerProvider } from '../provider.js'; -import { ServerError } from '../errors.js'; -import { FetchLike } from '../../../shared/transport.js'; - -export type ProxyEndpoints = { - authorizationUrl: string; - tokenUrl: string; - revocationUrl?: string; - registrationUrl?: string; -}; - -export type ProxyOptions = { - /** - * Individual endpoint URLs for proxying specific OAuth operations - */ - endpoints: ProxyEndpoints; - - /** - * Function to verify access tokens and return auth info - */ - verifyAccessToken: (token: string) => Promise; - - /** - * Function to fetch client information from the upstream server - */ - getClient: (clientId: string) => Promise; - - /** - * Custom fetch implementation used for all network requests. - */ - fetch?: FetchLike; -}; - -/** - * Implements an OAuth server that proxies requests to another OAuth server. - */ -export class ProxyOAuthServerProvider implements OAuthServerProvider { - protected readonly _endpoints: ProxyEndpoints; - protected readonly _verifyAccessToken: (token: string) => Promise; - protected readonly _getClient: (clientId: string) => Promise; - protected readonly _fetch?: FetchLike; - - skipLocalPkceValidation = true; - - revokeToken?: (client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest) => Promise; - - constructor(options: ProxyOptions) { - this._endpoints = options.endpoints; - this._verifyAccessToken = options.verifyAccessToken; - this._getClient = options.getClient; - this._fetch = options.fetch; - if (options.endpoints?.revocationUrl) { - this.revokeToken = async (client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest) => { - const revocationUrl = this._endpoints.revocationUrl; - - if (!revocationUrl) { - throw new Error('No revocation endpoint configured'); - } - - const params = new URLSearchParams(); - params.set('token', request.token); - params.set('client_id', client.client_id); - if (client.client_secret) { - params.set('client_secret', client.client_secret); - } - if (request.token_type_hint) { - params.set('token_type_hint', request.token_type_hint); - } - - const response = await (this._fetch ?? fetch)(revocationUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: params.toString() - }); - - if (!response.ok) { - throw new ServerError(`Token revocation failed: ${response.status}`); - } - }; - } - } - - get clientsStore(): OAuthRegisteredClientsStore { - const registrationUrl = this._endpoints.registrationUrl; - return { - getClient: this._getClient, - ...(registrationUrl && { - registerClient: async (client: OAuthClientInformationFull) => { - const response = await (this._fetch ?? fetch)(registrationUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(client) - }); - - if (!response.ok) { - throw new ServerError(`Client registration failed: ${response.status}`); - } - - const data = await response.json(); - return OAuthClientInformationFullSchema.parse(data); - } - }) - }; - } - - async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise { - // Start with required OAuth parameters - const targetUrl = new URL(this._endpoints.authorizationUrl); - const searchParams = new URLSearchParams({ - client_id: client.client_id, - response_type: 'code', - redirect_uri: params.redirectUri, - code_challenge: params.codeChallenge, - code_challenge_method: 'S256' - }); - - // Add optional standard OAuth parameters - if (params.state) searchParams.set('state', params.state); - if (params.scopes?.length) searchParams.set('scope', params.scopes.join(' ')); - if (params.resource) searchParams.set('resource', params.resource.href); - - targetUrl.search = searchParams.toString(); - res.redirect(targetUrl.toString()); - } - - async challengeForAuthorizationCode(_client: OAuthClientInformationFull, _authorizationCode: string): Promise { - // In a proxy setup, we don't store the code challenge ourselves - // Instead, we proxy the token request and let the upstream server validate it - return ''; - } - - async exchangeAuthorizationCode( - client: OAuthClientInformationFull, - authorizationCode: string, - codeVerifier?: string, - redirectUri?: string, - resource?: URL - ): Promise { - const params = new URLSearchParams({ - grant_type: 'authorization_code', - client_id: client.client_id, - code: authorizationCode - }); - - if (client.client_secret) { - params.append('client_secret', client.client_secret); - } - - if (codeVerifier) { - params.append('code_verifier', codeVerifier); - } - - if (redirectUri) { - params.append('redirect_uri', redirectUri); - } - - if (resource) { - params.append('resource', resource.href); - } - - const response = await (this._fetch ?? fetch)(this._endpoints.tokenUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: params.toString() - }); - - if (!response.ok) { - throw new ServerError(`Token exchange failed: ${response.status}`); - } - - const data = await response.json(); - return OAuthTokensSchema.parse(data); - } - - async exchangeRefreshToken( - client: OAuthClientInformationFull, - refreshToken: string, - scopes?: string[], - resource?: URL - ): Promise { - const params = new URLSearchParams({ - grant_type: 'refresh_token', - client_id: client.client_id, - refresh_token: refreshToken - }); - - if (client.client_secret) { - params.set('client_secret', client.client_secret); - } - - if (scopes?.length) { - params.set('scope', scopes.join(' ')); - } - - if (resource) { - params.set('resource', resource.href); - } - - const response = await (this._fetch ?? fetch)(this._endpoints.tokenUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: params.toString() - }); - - if (!response.ok) { - throw new ServerError(`Token refresh failed: ${response.status}`); - } - - const data = await response.json(); - return OAuthTokensSchema.parse(data); - } - - async verifyAccessToken(token: string): Promise { - return this._verifyAccessToken(token); - } -} diff --git a/typescript-sdk/src/server/auth/router.test.ts b/typescript-sdk/src/server/auth/router.test.ts deleted file mode 100644 index f2091bc..0000000 --- a/typescript-sdk/src/server/auth/router.test.ts +++ /dev/null @@ -1,463 +0,0 @@ -import { mcpAuthRouter, AuthRouterOptions, mcpAuthMetadataRouter, AuthMetadataOptions } from './router.js'; -import { OAuthServerProvider, AuthorizationParams } from './provider.js'; -import { OAuthRegisteredClientsStore } from './clients.js'; -import { OAuthClientInformationFull, OAuthMetadata, OAuthTokenRevocationRequest, OAuthTokens } from '../../shared/auth.js'; -import express, { Response } from 'express'; -import supertest from 'supertest'; -import { AuthInfo } from './types.js'; -import { InvalidTokenError } from './errors.js'; - -describe('MCP Auth Router', () => { - // Setup mock provider with full capabilities - const mockClientStore: OAuthRegisteredClientsStore = { - async getClient(clientId: string): Promise { - if (clientId === 'valid-client') { - return { - client_id: 'valid-client', - client_secret: 'valid-secret', - redirect_uris: ['https://example.com/callback'] - }; - } - return undefined; - }, - - async registerClient(client: OAuthClientInformationFull): Promise { - return client; - } - }; - - const mockProvider: OAuthServerProvider = { - clientsStore: mockClientStore, - - async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise { - const redirectUrl = new URL(params.redirectUri); - redirectUrl.searchParams.set('code', 'mock_auth_code'); - if (params.state) { - redirectUrl.searchParams.set('state', params.state); - } - res.redirect(302, redirectUrl.toString()); - }, - - async challengeForAuthorizationCode(): Promise { - return 'mock_challenge'; - }, - - async exchangeAuthorizationCode(): Promise { - return { - access_token: 'mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'mock_refresh_token' - }; - }, - - async exchangeRefreshToken(): Promise { - return { - access_token: 'new_mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'new_mock_refresh_token' - }; - }, - - async verifyAccessToken(token: string): Promise { - if (token === 'valid_token') { - return { - token, - clientId: 'valid-client', - scopes: ['read', 'write'], - expiresAt: Date.now() / 1000 + 3600 - }; - } - throw new InvalidTokenError('Token is invalid or expired'); - }, - - async revokeToken(_client: OAuthClientInformationFull, _request: OAuthTokenRevocationRequest): Promise { - // Success - do nothing in mock - } - }; - - // Provider without registration and revocation - const mockProviderMinimal: OAuthServerProvider = { - clientsStore: { - async getClient(clientId: string): Promise { - if (clientId === 'valid-client') { - return { - client_id: 'valid-client', - client_secret: 'valid-secret', - redirect_uris: ['https://example.com/callback'] - }; - } - return undefined; - } - }, - - async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise { - const redirectUrl = new URL(params.redirectUri); - redirectUrl.searchParams.set('code', 'mock_auth_code'); - if (params.state) { - redirectUrl.searchParams.set('state', params.state); - } - res.redirect(302, redirectUrl.toString()); - }, - - async challengeForAuthorizationCode(): Promise { - return 'mock_challenge'; - }, - - async exchangeAuthorizationCode(): Promise { - return { - access_token: 'mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'mock_refresh_token' - }; - }, - - async exchangeRefreshToken(): Promise { - return { - access_token: 'new_mock_access_token', - token_type: 'bearer', - expires_in: 3600, - refresh_token: 'new_mock_refresh_token' - }; - }, - - async verifyAccessToken(token: string): Promise { - if (token === 'valid_token') { - return { - token, - clientId: 'valid-client', - scopes: ['read'], - expiresAt: Date.now() / 1000 + 3600 - }; - } - throw new InvalidTokenError('Token is invalid or expired'); - } - }; - - describe('Router creation', () => { - it('throws error for non-HTTPS issuer URL', () => { - const options: AuthRouterOptions = { - provider: mockProvider, - issuerUrl: new URL('http://auth.example.com') - }; - - expect(() => mcpAuthRouter(options)).toThrow('Issuer URL must be HTTPS'); - }); - - it('allows localhost HTTP for development', () => { - const options: AuthRouterOptions = { - provider: mockProvider, - issuerUrl: new URL('http://localhost:3000') - }; - - expect(() => mcpAuthRouter(options)).not.toThrow(); - }); - - it('throws error for issuer URL with fragment', () => { - const options: AuthRouterOptions = { - provider: mockProvider, - issuerUrl: new URL('https://auth.example.com#fragment') - }; - - expect(() => mcpAuthRouter(options)).toThrow('Issuer URL must not have a fragment'); - }); - - it('throws error for issuer URL with query string', () => { - const options: AuthRouterOptions = { - provider: mockProvider, - issuerUrl: new URL('https://auth.example.com?param=value') - }; - - expect(() => mcpAuthRouter(options)).toThrow('Issuer URL must not have a query string'); - }); - - it('successfully creates router with valid options', () => { - const options: AuthRouterOptions = { - provider: mockProvider, - issuerUrl: new URL('https://auth.example.com') - }; - - expect(() => mcpAuthRouter(options)).not.toThrow(); - }); - }); - - describe('Metadata endpoint', () => { - let app: express.Express; - - beforeEach(() => { - // Setup full-featured router - app = express(); - const options: AuthRouterOptions = { - provider: mockProvider, - issuerUrl: new URL('https://auth.example.com'), - serviceDocumentationUrl: new URL('https://docs.example.com') - }; - app.use(mcpAuthRouter(options)); - }); - - it('returns complete metadata for full-featured router', async () => { - const response = await supertest(app).get('/.well-known/oauth-authorization-server'); - - expect(response.status).toBe(200); - - // Verify essential fields - expect(response.body.issuer).toBe('https://auth.example.com/'); - expect(response.body.authorization_endpoint).toBe('https://auth.example.com/authorize'); - expect(response.body.token_endpoint).toBe('https://auth.example.com/token'); - expect(response.body.registration_endpoint).toBe('https://auth.example.com/register'); - expect(response.body.revocation_endpoint).toBe('https://auth.example.com/revoke'); - - // Verify supported features - expect(response.body.response_types_supported).toEqual(['code']); - expect(response.body.grant_types_supported).toEqual(['authorization_code', 'refresh_token']); - expect(response.body.code_challenge_methods_supported).toEqual(['S256']); - expect(response.body.token_endpoint_auth_methods_supported).toEqual(['client_secret_post']); - expect(response.body.revocation_endpoint_auth_methods_supported).toEqual(['client_secret_post']); - - // Verify optional fields - expect(response.body.service_documentation).toBe('https://docs.example.com/'); - }); - - it('returns minimal metadata for minimal router', async () => { - // Setup minimal router - const minimalApp = express(); - const options: AuthRouterOptions = { - provider: mockProviderMinimal, - issuerUrl: new URL('https://auth.example.com') - }; - minimalApp.use(mcpAuthRouter(options)); - - const response = await supertest(minimalApp).get('/.well-known/oauth-authorization-server'); - - expect(response.status).toBe(200); - - // Verify essential endpoints - expect(response.body.issuer).toBe('https://auth.example.com/'); - expect(response.body.authorization_endpoint).toBe('https://auth.example.com/authorize'); - expect(response.body.token_endpoint).toBe('https://auth.example.com/token'); - - // Verify missing optional endpoints - expect(response.body.registration_endpoint).toBeUndefined(); - expect(response.body.revocation_endpoint).toBeUndefined(); - expect(response.body.revocation_endpoint_auth_methods_supported).toBeUndefined(); - expect(response.body.service_documentation).toBeUndefined(); - }); - - it('provides protected resource metadata', async () => { - // Setup router with draft protocol version - const draftApp = express(); - const options: AuthRouterOptions = { - provider: mockProvider, - issuerUrl: new URL('https://mcp.example.com'), - scopesSupported: ['read', 'write'], - resourceName: 'Test API' - }; - draftApp.use(mcpAuthRouter(options)); - - const response = await supertest(draftApp).get('/.well-known/oauth-protected-resource'); - - expect(response.status).toBe(200); - - // Verify protected resource metadata - expect(response.body.resource).toBe('https://mcp.example.com/'); - expect(response.body.authorization_servers).toContain('https://mcp.example.com/'); - expect(response.body.scopes_supported).toEqual(['read', 'write']); - expect(response.body.resource_name).toBe('Test API'); - }); - }); - - describe('Endpoint routing', () => { - let app: express.Express; - - beforeEach(() => { - // Setup full-featured router - app = express(); - const options: AuthRouterOptions = { - provider: mockProvider, - issuerUrl: new URL('https://auth.example.com') - }; - app.use(mcpAuthRouter(options)); - jest.spyOn(console, 'error').mockImplementation(() => {}); - }); - - afterEach(() => { - jest.restoreAllMocks(); - }); - - it('routes to authorization endpoint', async () => { - const response = await supertest(app).get('/authorize').query({ - client_id: 'valid-client', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256' - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.searchParams.has('code')).toBe(true); - }); - - it('routes to token endpoint', async () => { - // Setup verifyChallenge mock for token handler - jest.mock('pkce-challenge', () => ({ - verifyChallenge: jest.fn().mockResolvedValue(true) - })); - - const response = await supertest(app).post('/token').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'valid_verifier' - }); - - // The request will fail in testing due to mocking limitations, - // but we can verify the route was matched - expect(response.status).not.toBe(404); - }); - - it('routes to registration endpoint', async () => { - const response = await supertest(app) - .post('/register') - .send({ - redirect_uris: ['https://example.com/callback'] - }); - - // The request will fail in testing due to mocking limitations, - // but we can verify the route was matched - expect(response.status).not.toBe(404); - }); - - it('routes to revocation endpoint', async () => { - const response = await supertest(app).post('/revoke').type('form').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - token: 'token_to_revoke' - }); - - // The request will fail in testing due to mocking limitations, - // but we can verify the route was matched - expect(response.status).not.toBe(404); - }); - - it('excludes endpoints for unsupported features', async () => { - // Setup minimal router - const minimalApp = express(); - const options: AuthRouterOptions = { - provider: mockProviderMinimal, - issuerUrl: new URL('https://auth.example.com') - }; - minimalApp.use(mcpAuthRouter(options)); - - // Registration should not be available - const regResponse = await supertest(minimalApp) - .post('/register') - .send({ - redirect_uris: ['https://example.com/callback'] - }); - expect(regResponse.status).toBe(404); - - // Revocation should not be available - const revokeResponse = await supertest(minimalApp).post('/revoke').send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - token: 'token_to_revoke' - }); - expect(revokeResponse.status).toBe(404); - }); - }); -}); - -describe('MCP Auth Metadata Router', () => { - const mockOAuthMetadata: OAuthMetadata = { - issuer: 'https://auth.example.com/', - authorization_endpoint: 'https://auth.example.com/authorize', - token_endpoint: 'https://auth.example.com/token', - response_types_supported: ['code'], - grant_types_supported: ['authorization_code', 'refresh_token'], - code_challenge_methods_supported: ['S256'], - token_endpoint_auth_methods_supported: ['client_secret_post'] - }; - - describe('Router creation', () => { - it('successfully creates router with valid options', () => { - const options: AuthMetadataOptions = { - oauthMetadata: mockOAuthMetadata, - resourceServerUrl: new URL('https://api.example.com') - }; - - expect(() => mcpAuthMetadataRouter(options)).not.toThrow(); - }); - }); - - describe('Metadata endpoints', () => { - let app: express.Express; - - beforeEach(() => { - app = express(); - const options: AuthMetadataOptions = { - oauthMetadata: mockOAuthMetadata, - resourceServerUrl: new URL('https://api.example.com'), - serviceDocumentationUrl: new URL('https://docs.example.com'), - scopesSupported: ['read', 'write'], - resourceName: 'Test API' - }; - app.use(mcpAuthMetadataRouter(options)); - }); - - it('returns OAuth authorization server metadata', async () => { - const response = await supertest(app).get('/.well-known/oauth-authorization-server'); - - expect(response.status).toBe(200); - - // Verify metadata points to authorization server - expect(response.body.issuer).toBe('https://auth.example.com/'); - expect(response.body.authorization_endpoint).toBe('https://auth.example.com/authorize'); - expect(response.body.token_endpoint).toBe('https://auth.example.com/token'); - expect(response.body.response_types_supported).toEqual(['code']); - expect(response.body.grant_types_supported).toEqual(['authorization_code', 'refresh_token']); - expect(response.body.code_challenge_methods_supported).toEqual(['S256']); - expect(response.body.token_endpoint_auth_methods_supported).toEqual(['client_secret_post']); - }); - - it('returns OAuth protected resource metadata', async () => { - const response = await supertest(app).get('/.well-known/oauth-protected-resource'); - - expect(response.status).toBe(200); - - // Verify protected resource metadata - expect(response.body.resource).toBe('https://api.example.com/'); - expect(response.body.authorization_servers).toEqual(['https://auth.example.com/']); - expect(response.body.scopes_supported).toEqual(['read', 'write']); - expect(response.body.resource_name).toBe('Test API'); - expect(response.body.resource_documentation).toBe('https://docs.example.com/'); - }); - - it('works with minimal configuration', async () => { - const minimalApp = express(); - const options: AuthMetadataOptions = { - oauthMetadata: mockOAuthMetadata, - resourceServerUrl: new URL('https://api.example.com') - }; - minimalApp.use(mcpAuthMetadataRouter(options)); - - const authResponse = await supertest(minimalApp).get('/.well-known/oauth-authorization-server'); - - expect(authResponse.status).toBe(200); - expect(authResponse.body.issuer).toBe('https://auth.example.com/'); - expect(authResponse.body.service_documentation).toBeUndefined(); - expect(authResponse.body.scopes_supported).toBeUndefined(); - - const resourceResponse = await supertest(minimalApp).get('/.well-known/oauth-protected-resource'); - - expect(resourceResponse.status).toBe(200); - expect(resourceResponse.body.resource).toBe('https://api.example.com/'); - expect(resourceResponse.body.authorization_servers).toEqual(['https://auth.example.com/']); - expect(resourceResponse.body.scopes_supported).toBeUndefined(); - expect(resourceResponse.body.resource_name).toBeUndefined(); - expect(resourceResponse.body.resource_documentation).toBeUndefined(); - }); - }); -}); diff --git a/typescript-sdk/src/server/auth/router.ts b/typescript-sdk/src/server/auth/router.ts deleted file mode 100644 index dc0a85a..0000000 --- a/typescript-sdk/src/server/auth/router.ts +++ /dev/null @@ -1,232 +0,0 @@ -import express, { RequestHandler } from 'express'; -import { clientRegistrationHandler, ClientRegistrationHandlerOptions } from './handlers/register.js'; -import { tokenHandler, TokenHandlerOptions } from './handlers/token.js'; -import { authorizationHandler, AuthorizationHandlerOptions } from './handlers/authorize.js'; -import { revocationHandler, RevocationHandlerOptions } from './handlers/revoke.js'; -import { metadataHandler } from './handlers/metadata.js'; -import { OAuthServerProvider } from './provider.js'; -import { OAuthMetadata, OAuthProtectedResourceMetadata } from '../../shared/auth.js'; - -export type AuthRouterOptions = { - /** - * A provider implementing the actual authorization logic for this router. - */ - provider: OAuthServerProvider; - - /** - * The authorization server's issuer identifier, which is a URL that uses the "https" scheme and has no query or fragment components. - */ - issuerUrl: URL; - - /** - * The base URL of the authorization server to use for the metadata endpoints. - * - * If not provided, the issuer URL will be used as the base URL. - */ - baseUrl?: URL; - - /** - * An optional URL of a page containing human-readable information that developers might want or need to know when using the authorization server. - */ - serviceDocumentationUrl?: URL; - - /** - * An optional list of scopes supported by this authorization server - */ - scopesSupported?: string[]; - - /** - * The resource name to be displayed in protected resource metadata - */ - resourceName?: string; - - /** - * The URL of the protected resource (RS) whose metadata we advertise. - * If not provided, falls back to `baseUrl` and then to `issuerUrl` (AS=RS). - */ - resourceServerUrl?: URL; - - // Individual options per route - authorizationOptions?: Omit; - clientRegistrationOptions?: Omit; - revocationOptions?: Omit; - tokenOptions?: Omit; -}; - -const checkIssuerUrl = (issuer: URL): void => { - // Technically RFC 8414 does not permit a localhost HTTPS exemption, but this will be necessary for ease of testing - if (issuer.protocol !== 'https:' && issuer.hostname !== 'localhost' && issuer.hostname !== '127.0.0.1') { - throw new Error('Issuer URL must be HTTPS'); - } - if (issuer.hash) { - throw new Error(`Issuer URL must not have a fragment: ${issuer}`); - } - if (issuer.search) { - throw new Error(`Issuer URL must not have a query string: ${issuer}`); - } -}; - -export const createOAuthMetadata = (options: { - provider: OAuthServerProvider; - issuerUrl: URL; - baseUrl?: URL; - serviceDocumentationUrl?: URL; - scopesSupported?: string[]; -}): OAuthMetadata => { - const issuer = options.issuerUrl; - const baseUrl = options.baseUrl; - - checkIssuerUrl(issuer); - - const authorization_endpoint = '/authorize'; - const token_endpoint = '/token'; - const registration_endpoint = options.provider.clientsStore.registerClient ? '/register' : undefined; - const revocation_endpoint = options.provider.revokeToken ? '/revoke' : undefined; - - const metadata: OAuthMetadata = { - issuer: issuer.href, - service_documentation: options.serviceDocumentationUrl?.href, - - authorization_endpoint: new URL(authorization_endpoint, baseUrl || issuer).href, - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'], - - token_endpoint: new URL(token_endpoint, baseUrl || issuer).href, - token_endpoint_auth_methods_supported: ['client_secret_post'], - grant_types_supported: ['authorization_code', 'refresh_token'], - - scopes_supported: options.scopesSupported, - - revocation_endpoint: revocation_endpoint ? new URL(revocation_endpoint, baseUrl || issuer).href : undefined, - revocation_endpoint_auth_methods_supported: revocation_endpoint ? ['client_secret_post'] : undefined, - - registration_endpoint: registration_endpoint ? new URL(registration_endpoint, baseUrl || issuer).href : undefined - }; - - return metadata; -}; - -/** - * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). - * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. - * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. - * - * By default, rate limiting is applied to all endpoints to prevent abuse. - * - * This router MUST be installed at the application root, like so: - * - * const app = express(); - * app.use(mcpAuthRouter(...)); - */ -export function mcpAuthRouter(options: AuthRouterOptions): RequestHandler { - const oauthMetadata = createOAuthMetadata(options); - - const router = express.Router(); - - router.use( - new URL(oauthMetadata.authorization_endpoint).pathname, - authorizationHandler({ provider: options.provider, ...options.authorizationOptions }) - ); - - router.use(new URL(oauthMetadata.token_endpoint).pathname, tokenHandler({ provider: options.provider, ...options.tokenOptions })); - - router.use( - mcpAuthMetadataRouter({ - oauthMetadata, - // Prefer explicit RS; otherwise fall back to AS baseUrl, then to issuer (back-compat) - resourceServerUrl: options.resourceServerUrl ?? options.baseUrl ?? new URL(oauthMetadata.issuer), - serviceDocumentationUrl: options.serviceDocumentationUrl, - scopesSupported: options.scopesSupported, - resourceName: options.resourceName - }) - ); - - if (oauthMetadata.registration_endpoint) { - router.use( - new URL(oauthMetadata.registration_endpoint).pathname, - clientRegistrationHandler({ - clientsStore: options.provider.clientsStore, - ...options.clientRegistrationOptions - }) - ); - } - - if (oauthMetadata.revocation_endpoint) { - router.use( - new URL(oauthMetadata.revocation_endpoint).pathname, - revocationHandler({ provider: options.provider, ...options.revocationOptions }) - ); - } - - return router; -} - -export type AuthMetadataOptions = { - /** - * OAuth Metadata as would be returned from the authorization server - * this MCP server relies on - */ - oauthMetadata: OAuthMetadata; - - /** - * The url of the MCP server, for use in protected resource metadata - */ - resourceServerUrl: URL; - - /** - * The url for documentation for the MCP server - */ - serviceDocumentationUrl?: URL; - - /** - * An optional list of scopes supported by this MCP server - */ - scopesSupported?: string[]; - - /** - * An optional resource name to display in resource metadata - */ - resourceName?: string; -}; - -export function mcpAuthMetadataRouter(options: AuthMetadataOptions): express.Router { - checkIssuerUrl(new URL(options.oauthMetadata.issuer)); - - const router = express.Router(); - - const protectedResourceMetadata: OAuthProtectedResourceMetadata = { - resource: options.resourceServerUrl.href, - - authorization_servers: [options.oauthMetadata.issuer], - - scopes_supported: options.scopesSupported, - resource_name: options.resourceName, - resource_documentation: options.serviceDocumentationUrl?.href - }; - - // Serve PRM at the path-specific URL per RFC 9728 - const rsPath = new URL(options.resourceServerUrl.href).pathname; - router.use(`/.well-known/oauth-protected-resource${rsPath === '/' ? '' : rsPath}`, metadataHandler(protectedResourceMetadata)); - - // Always add this for OAuth Authorization Server metadata per RFC 8414 - router.use('/.well-known/oauth-authorization-server', metadataHandler(options.oauthMetadata)); - - return router; -} - -/** - * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL - * from a given server URL. This replaces the path with the standard metadata endpoint. - * - * @param serverUrl - The base URL of the protected resource server - * @returns The URL for the OAuth protected resource metadata endpoint - * - * @example - * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) - * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' - */ -export function getOAuthProtectedResourceMetadataUrl(serverUrl: URL): string { - const u = new URL(serverUrl.href); - const rsPath = u.pathname && u.pathname !== '/' ? u.pathname : ''; - return new URL(`/.well-known/oauth-protected-resource${rsPath}`, u).href; -} diff --git a/typescript-sdk/src/server/auth/types.ts b/typescript-sdk/src/server/auth/types.ts deleted file mode 100644 index a38a7e7..0000000 --- a/typescript-sdk/src/server/auth/types.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Information about a validated access token, provided to request handlers. - */ -export interface AuthInfo { - /** - * The access token. - */ - token: string; - - /** - * The client ID associated with this token. - */ - clientId: string; - - /** - * Scopes associated with this token. - */ - scopes: string[]; - - /** - * When the token expires (in seconds since epoch). - */ - expiresAt?: number; - - /** - * The RFC 8707 resource server identifier for which this token is valid. - * If set, this MUST match the MCP server's resource identifier (minus hash fragment). - */ - resource?: URL; - - /** - * Additional data associated with the token. - * This field should be used for any additional data that needs to be attached to the auth info. - */ - extra?: Record; -} diff --git a/typescript-sdk/src/server/completable.test.ts b/typescript-sdk/src/server/completable.test.ts deleted file mode 100644 index b5effc2..0000000 --- a/typescript-sdk/src/server/completable.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { z } from 'zod'; -import { completable } from './completable.js'; - -describe('completable', () => { - it('preserves types and values of underlying schema', () => { - const baseSchema = z.string(); - const schema = completable(baseSchema, () => []); - - expect(schema.parse('test')).toBe('test'); - expect(() => schema.parse(123)).toThrow(); - }); - - it('provides access to completion function', async () => { - const completions = ['foo', 'bar', 'baz']; - const schema = completable(z.string(), () => completions); - - expect(await schema._def.complete('')).toEqual(completions); - }); - - it('allows async completion functions', async () => { - const completions = ['foo', 'bar', 'baz']; - const schema = completable(z.string(), async () => completions); - - expect(await schema._def.complete('')).toEqual(completions); - }); - - it('passes current value to completion function', async () => { - const schema = completable(z.string(), value => [value + '!']); - - expect(await schema._def.complete('test')).toEqual(['test!']); - }); - - it('works with number schemas', async () => { - const schema = completable(z.number(), () => [1, 2, 3]); - - expect(schema.parse(1)).toBe(1); - expect(await schema._def.complete(0)).toEqual([1, 2, 3]); - }); - - it('preserves schema description', () => { - const desc = 'test description'; - const schema = completable(z.string().describe(desc), () => []); - - expect(schema.description).toBe(desc); - }); -}); diff --git a/typescript-sdk/src/server/completable.ts b/typescript-sdk/src/server/completable.ts deleted file mode 100644 index 67d91c3..0000000 --- a/typescript-sdk/src/server/completable.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { ZodTypeAny, ZodTypeDef, ZodType, ParseInput, ParseReturnType, RawCreateParams, ZodErrorMap, ProcessedCreateParams } from 'zod'; - -export enum McpZodTypeKind { - Completable = 'McpCompletable' -} - -export type CompleteCallback = ( - value: T['_input'], - context?: { - arguments?: Record; - } -) => T['_input'][] | Promise; - -export interface CompletableDef extends ZodTypeDef { - type: T; - complete: CompleteCallback; - typeName: McpZodTypeKind.Completable; -} - -export class Completable extends ZodType, T['_input']> { - _parse(input: ParseInput): ParseReturnType { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - - unwrap() { - return this._def.type; - } - - static create = ( - type: T, - params: RawCreateParams & { - complete: CompleteCallback; - } - ): Completable => { - return new Completable({ - type, - typeName: McpZodTypeKind.Completable, - complete: params.complete, - ...processCreateParams(params) - }); - }; -} - -/** - * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. - */ -export function completable(schema: T, complete: CompleteCallback): Completable { - return Completable.create(schema, { ...schema._def, complete }); -} - -// Not sure why this isn't exported from Zod: -// https://github.com/colinhacks/zod/blob/f7ad26147ba291cb3fb257545972a8e00e767470/src/types.ts#L130 -function processCreateParams(params: RawCreateParams): ProcessedCreateParams { - if (!params) return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap) return { errorMap: errorMap, description }; - const customMap: ZodErrorMap = (iss, ctx) => { - const { message } = params; - - if (iss.code === 'invalid_enum_value') { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === 'undefined') { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== 'invalid_type') return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} diff --git a/typescript-sdk/src/server/elicitation.test.ts b/typescript-sdk/src/server/elicitation.test.ts deleted file mode 100644 index 845a08c..0000000 --- a/typescript-sdk/src/server/elicitation.test.ts +++ /dev/null @@ -1,642 +0,0 @@ -/** - * Comprehensive elicitation flow tests with validator integration - * - * These tests verify the end-to-end elicitation flow from server requesting - * input to client responding and validation of the response against schemas. - * - * Per the MCP spec, elicitation only supports object schemas, not primitives. - */ - -import { Client } from '../client/index.js'; -import { InMemoryTransport } from '../inMemory.js'; -import { ElicitRequestSchema } from '../types.js'; -import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; -import { CfWorkerJsonSchemaValidator } from '../validation/cfworker-provider.js'; -import { Server } from './index.js'; - -const ajvProvider = new AjvJsonSchemaValidator(); -const cfWorkerProvider = new CfWorkerJsonSchemaValidator(); - -describe('Elicitation Flow', () => { - describe('with AJV validator', () => { - testElicitationFlow(ajvProvider, 'AJV'); - }); - - describe('with CfWorker validator', () => { - testElicitationFlow(cfWorkerProvider, 'CfWorker'); - }); -}); - -function testElicitationFlow(validatorProvider: typeof ajvProvider | typeof cfWorkerProvider, validatorName: string) { - test(`${validatorName}: should elicit simple object with string field`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { name: 'John Doe' } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const result = await server.elicitInput({ - message: 'What is your name?', - requestedSchema: { - type: 'object', - properties: { - name: { type: 'string', minLength: 1 } - }, - required: ['name'] - } - }); - - expect(result).toEqual({ - action: 'accept', - content: { name: 'John Doe' } - }); - }); - - test(`${validatorName}: should elicit object with integer field`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { age: 42 } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const result = await server.elicitInput({ - message: 'What is your age?', - requestedSchema: { - type: 'object', - properties: { - age: { type: 'integer', minimum: 0, maximum: 150 } - }, - required: ['age'] - } - }); - - expect(result).toEqual({ - action: 'accept', - content: { age: 42 } - }); - }); - - test(`${validatorName}: should elicit object with boolean field`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { agree: true } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const result = await server.elicitInput({ - message: 'Do you agree?', - requestedSchema: { - type: 'object', - properties: { - agree: { type: 'boolean' } - }, - required: ['agree'] - } - }); - - expect(result).toEqual({ - action: 'accept', - content: { agree: true } - }); - }); - - test(`${validatorName}: should elicit complex object with multiple fields`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - const userData = { - name: 'Jane Smith', - email: 'jane@example.com', - age: 28, - street: '123 Main St', - city: 'San Francisco', - zipCode: '94105', - newsletter: true, - notifications: false - }; - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: userData - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const result = await server.elicitInput({ - message: 'Please provide your information', - requestedSchema: { - type: 'object', - properties: { - name: { type: 'string', minLength: 1 }, - email: { type: 'string', format: 'email' }, - age: { type: 'integer', minimum: 0, maximum: 150 }, - street: { type: 'string' }, - city: { type: 'string' }, - zipCode: { type: 'string', pattern: '^[0-9]{5}$' }, - newsletter: { type: 'boolean' }, - notifications: { type: 'boolean' } - }, - required: ['name', 'email', 'age', 'street', 'city', 'zipCode'] - } - }); - - expect(result).toEqual({ - action: 'accept', - content: userData - }); - }); - - test(`${validatorName}: should reject invalid object (missing required field)`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { - email: 'user@example.com' - // Missing required 'name' field - } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - await expect( - server.elicitInput({ - message: 'Please provide your information', - requestedSchema: { - type: 'object', - properties: { - name: { type: 'string' }, - email: { type: 'string' } - }, - required: ['name', 'email'] - } - }) - ).rejects.toThrow(/does not match requested schema/); - }); - - test(`${validatorName}: should reject invalid field type`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { - name: 'John Doe', - age: 'thirty' // Wrong type - should be integer - } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - await expect( - server.elicitInput({ - message: 'Please provide your information', - requestedSchema: { - type: 'object', - properties: { - name: { type: 'string' }, - age: { type: 'integer' } - }, - required: ['name', 'age'] - } - }) - ).rejects.toThrow(/does not match requested schema/); - }); - - test(`${validatorName}: should reject invalid string (too short)`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { name: '' } // Too short - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - await expect( - server.elicitInput({ - message: 'What is your name?', - requestedSchema: { - type: 'object', - properties: { - name: { type: 'string', minLength: 1 } - }, - required: ['name'] - } - }) - ).rejects.toThrow(/does not match requested schema/); - }); - - test(`${validatorName}: should reject invalid integer (out of range)`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { age: 200 } // Too high - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - await expect( - server.elicitInput({ - message: 'What is your age?', - requestedSchema: { - type: 'object', - properties: { - age: { type: 'integer', minimum: 0, maximum: 150 } - }, - required: ['age'] - } - }) - ).rejects.toThrow(/does not match requested schema/); - }); - - test(`${validatorName}: should reject invalid pattern`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { zipCode: 'ABC123' } // Doesn't match pattern - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - await expect( - server.elicitInput({ - message: 'Enter a 5-digit zip code', - requestedSchema: { - type: 'object', - properties: { - zipCode: { type: 'string', pattern: '^[0-9]{5}$' } - }, - required: ['zipCode'] - } - }) - ).rejects.toThrow(/does not match requested schema/); - }); - - test(`${validatorName}: should allow decline action without validation`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'decline' - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const result = await server.elicitInput({ - message: 'Please provide your information', - requestedSchema: { - type: 'object', - properties: { - name: { type: 'string' } - }, - required: ['name'] - } - }); - - expect(result).toEqual({ - action: 'decline' - }); - }); - - test(`${validatorName}: should allow cancel action without validation`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'cancel' - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const result = await server.elicitInput({ - message: 'Please provide your information', - requestedSchema: { - type: 'object', - properties: { - name: { type: 'string' } - }, - required: ['name'] - } - }); - - expect(result).toEqual({ - action: 'cancel' - }); - }); - - test(`${validatorName}: should handle multiple sequential elicitation requests`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - let requestCount = 0; - client.setRequestHandler(ElicitRequestSchema, request => { - requestCount++; - if (request.params.message.includes('name')) { - return { action: 'accept', content: { name: 'Alice' } }; - } else if (request.params.message.includes('age')) { - return { action: 'accept', content: { age: 30 } }; - } else if (request.params.message.includes('city')) { - return { action: 'accept', content: { city: 'New York' } }; - } - return { action: 'decline' }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const nameResult = await server.elicitInput({ - message: 'What is your name?', - requestedSchema: { - type: 'object', - properties: { name: { type: 'string', minLength: 1 } }, - required: ['name'] - } - }); - - const ageResult = await server.elicitInput({ - message: 'What is your age?', - requestedSchema: { - type: 'object', - properties: { age: { type: 'integer', minimum: 0 } }, - required: ['age'] - } - }); - - const cityResult = await server.elicitInput({ - message: 'What is your city?', - requestedSchema: { - type: 'object', - properties: { city: { type: 'string', minLength: 1 } }, - required: ['city'] - } - }); - - expect(requestCount).toBe(3); - expect(nameResult).toEqual({ - action: 'accept', - content: { name: 'Alice' } - }); - expect(ageResult).toEqual({ action: 'accept', content: { age: 30 } }); - expect(cityResult).toEqual({ - action: 'accept', - content: { city: 'New York' } - }); - }); - - test(`${validatorName}: should validate with optional fields present`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { name: 'John', nickname: 'Johnny' } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const result = await server.elicitInput({ - message: 'Enter your name', - requestedSchema: { - type: 'object', - properties: { - name: { type: 'string', minLength: 1 }, - nickname: { type: 'string' } - }, - required: ['name'] - } - }); - - expect(result).toEqual({ - action: 'accept', - content: { name: 'John', nickname: 'Johnny' } - }); - }); - - test(`${validatorName}: should validate with optional fields absent`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { name: 'John' } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const result = await server.elicitInput({ - message: 'Enter your name', - requestedSchema: { - type: 'object', - properties: { - name: { type: 'string', minLength: 1 }, - nickname: { type: 'string' } - }, - required: ['name'] - } - }); - - expect(result).toEqual({ - action: 'accept', - content: { name: 'John' } - }); - }); - - test(`${validatorName}: should validate email format`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { email: 'user@example.com' } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const result = await server.elicitInput({ - message: 'Enter your email', - requestedSchema: { - type: 'object', - properties: { - email: { type: 'string', format: 'email' } - }, - required: ['email'] - } - }); - - expect(result).toEqual({ - action: 'accept', - content: { email: 'user@example.com' } - }); - }); - - test(`${validatorName}: should reject invalid email format`, async () => { - const server = new Server( - { name: 'test-server', version: '1.0.0' }, - { - capabilities: {}, - jsonSchemaValidator: validatorProvider - } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { elicitation: {} } }); - - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { email: 'not-an-email' } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - await expect( - server.elicitInput({ - message: 'Enter your email', - requestedSchema: { - type: 'object', - properties: { - email: { type: 'string', format: 'email' } - }, - required: ['email'] - } - }) - ).rejects.toThrow(/does not match requested schema/); - }); -} diff --git a/typescript-sdk/src/server/index.test.ts b/typescript-sdk/src/server/index.test.ts deleted file mode 100644 index bea9c31..0000000 --- a/typescript-sdk/src/server/index.test.ts +++ /dev/null @@ -1,955 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { z } from 'zod'; -import { Client } from '../client/index.js'; -import { InMemoryTransport } from '../inMemory.js'; -import type { Transport } from '../shared/transport.js'; -import { - CreateMessageRequestSchema, - ElicitRequestSchema, - ErrorCode, - LATEST_PROTOCOL_VERSION, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListToolsRequestSchema, - type LoggingMessageNotification, - NotificationSchema, - RequestSchema, - ResultSchema, - SetLevelRequestSchema, - SUPPORTED_PROTOCOL_VERSIONS -} from '../types.js'; -import { Server } from './index.js'; - -test('should accept latest protocol version', async () => { - let sendPromiseResolve: (value: unknown) => void; - const sendPromise = new Promise(resolve => { - sendPromiseResolve = resolve; - }); - - const serverTransport: Transport = { - start: jest.fn().mockResolvedValue(undefined), - close: jest.fn().mockResolvedValue(undefined), - send: jest.fn().mockImplementation(message => { - if (message.id === 1 && message.result) { - expect(message.result).toEqual({ - protocolVersion: LATEST_PROTOCOL_VERSION, - capabilities: expect.any(Object), - serverInfo: { - name: 'test server', - version: '1.0' - }, - instructions: 'Test instructions' - }); - sendPromiseResolve(undefined); - } - return Promise.resolve(); - }) - }; - - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - }, - instructions: 'Test instructions' - } - ); - - await server.connect(serverTransport); - - // Simulate initialize request with latest version - serverTransport.onmessage?.({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: LATEST_PROTOCOL_VERSION, - capabilities: {}, - clientInfo: { - name: 'test client', - version: '1.0' - } - } - }); - - await expect(sendPromise).resolves.toBeUndefined(); -}); - -test('should accept supported older protocol version', async () => { - const OLD_VERSION = SUPPORTED_PROTOCOL_VERSIONS[1]; - let sendPromiseResolve: (value: unknown) => void; - const sendPromise = new Promise(resolve => { - sendPromiseResolve = resolve; - }); - - const serverTransport: Transport = { - start: jest.fn().mockResolvedValue(undefined), - close: jest.fn().mockResolvedValue(undefined), - send: jest.fn().mockImplementation(message => { - if (message.id === 1 && message.result) { - expect(message.result).toEqual({ - protocolVersion: OLD_VERSION, - capabilities: expect.any(Object), - serverInfo: { - name: 'test server', - version: '1.0' - } - }); - sendPromiseResolve(undefined); - } - return Promise.resolve(); - }) - }; - - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - } - } - ); - - await server.connect(serverTransport); - - // Simulate initialize request with older version - serverTransport.onmessage?.({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: OLD_VERSION, - capabilities: {}, - clientInfo: { - name: 'test client', - version: '1.0' - } - } - }); - - await expect(sendPromise).resolves.toBeUndefined(); -}); - -test('should handle unsupported protocol version', async () => { - let sendPromiseResolve: (value: unknown) => void; - const sendPromise = new Promise(resolve => { - sendPromiseResolve = resolve; - }); - - const serverTransport: Transport = { - start: jest.fn().mockResolvedValue(undefined), - close: jest.fn().mockResolvedValue(undefined), - send: jest.fn().mockImplementation(message => { - if (message.id === 1 && message.result) { - expect(message.result).toEqual({ - protocolVersion: LATEST_PROTOCOL_VERSION, - capabilities: expect.any(Object), - serverInfo: { - name: 'test server', - version: '1.0' - } - }); - sendPromiseResolve(undefined); - } - return Promise.resolve(); - }) - }; - - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - } - } - ); - - await server.connect(serverTransport); - - // Simulate initialize request with unsupported version - serverTransport.onmessage?.({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: 'invalid-version', - capabilities: {}, - clientInfo: { - name: 'test client', - version: '1.0' - } - } - }); - - await expect(sendPromise).resolves.toBeUndefined(); -}); - -test('should respect client capabilities', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - }, - enforceStrictCapabilities: true - } - ); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - // Implement request handler for sampling/createMessage - client.setRequestHandler(CreateMessageRequestSchema, async _request => { - // Mock implementation of createMessage - return { - model: 'test-model', - role: 'assistant', - content: { - type: 'text', - text: 'This is a test response' - } - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - expect(server.getClientCapabilities()).toEqual({ sampling: {} }); - - // This should work because sampling is supported by the client - await expect( - server.createMessage({ - messages: [], - maxTokens: 10 - }) - ).resolves.not.toThrow(); - - // This should still throw because roots are not supported by the client - await expect(server.listRoots()).rejects.toThrow(/^Client does not support/); -}); - -test('should respect client elicitation capabilities', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - }, - enforceStrictCapabilities: true - } - ); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - elicitation: {} - } - } - ); - - client.setRequestHandler(ElicitRequestSchema, params => ({ - action: 'accept', - content: { - username: params.params.message.includes('username') ? 'test-user' : undefined, - confirmed: true - } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - expect(server.getClientCapabilities()).toEqual({ elicitation: {} }); - - // This should work because elicitation is supported by the client - await expect( - server.elicitInput({ - message: 'Please provide your username', - requestedSchema: { - type: 'object', - properties: { - username: { - type: 'string', - title: 'Username', - description: 'Your username' - }, - confirmed: { - type: 'boolean', - title: 'Confirm', - description: 'Please confirm', - default: false - } - }, - required: ['username'] - } - }) - ).resolves.toEqual({ - action: 'accept', - content: { - username: 'test-user', - confirmed: true - } - }); - - // This should still throw because sampling is not supported by the client - await expect( - server.createMessage({ - messages: [], - maxTokens: 10 - }) - ).rejects.toThrow(/^Client does not support/); -}); - -test('should validate elicitation response against requested schema', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - }, - enforceStrictCapabilities: true - } - ); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - elicitation: {} - } - } - ); - - // Set up client to return valid response - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { - name: 'John Doe', - email: 'john@example.com', - age: 30 - } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // Test with valid response - await expect( - server.elicitInput({ - message: 'Please provide your information', - requestedSchema: { - type: 'object', - properties: { - name: { - type: 'string', - minLength: 1 - }, - email: { - type: 'string', - minLength: 1 - }, - age: { - type: 'integer', - minimum: 0, - maximum: 150 - } - }, - required: ['name', 'email'] - } - }) - ).resolves.toEqual({ - action: 'accept', - content: { - name: 'John Doe', - email: 'john@example.com', - age: 30 - } - }); -}); - -test('should reject elicitation response with invalid data', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - }, - enforceStrictCapabilities: true - } - ); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - elicitation: {} - } - } - ); - - // Set up client to return invalid response (missing required field, invalid age) - client.setRequestHandler(ElicitRequestSchema, _request => ({ - action: 'accept', - content: { - email: '', // Invalid - too short - age: -5 // Invalid age - } - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // Test with invalid response - await expect( - server.elicitInput({ - message: 'Please provide your information', - requestedSchema: { - type: 'object', - properties: { - name: { - type: 'string', - minLength: 1 - }, - email: { - type: 'string', - minLength: 1 - }, - age: { - type: 'integer', - minimum: 0, - maximum: 150 - } - }, - required: ['name', 'email'] - } - }) - ).rejects.toThrow(/does not match requested schema/); -}); - -test('should allow elicitation reject and cancel without validation', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - }, - enforceStrictCapabilities: true - } - ); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - elicitation: {} - } - } - ); - - let requestCount = 0; - client.setRequestHandler(ElicitRequestSchema, _request => { - requestCount++; - if (requestCount === 1) { - return { action: 'decline' }; - } else { - return { action: 'cancel' }; - } - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - const schema = { - type: 'object' as const, - properties: { - name: { type: 'string' as const } - }, - required: ['name'] - }; - - // Test reject - should not validate - await expect( - server.elicitInput({ - message: 'Please provide your name', - requestedSchema: schema - }) - ).resolves.toEqual({ - action: 'decline' - }); - - // Test cancel - should not validate - await expect( - server.elicitInput({ - message: 'Please provide your name', - requestedSchema: schema - }) - ).resolves.toEqual({ - action: 'cancel' - }); -}); - -test('should respect server notification capabilities', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - logging: {} - }, - enforceStrictCapabilities: true - } - ); - - const [_clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await server.connect(serverTransport); - - // This should work because logging is supported by the server - await expect( - server.sendLoggingMessage({ - level: 'info', - data: 'Test log message' - }) - ).resolves.not.toThrow(); - - // This should throw because resource notificaitons are not supported by the server - await expect(server.sendResourceUpdated({ uri: 'test://resource' })).rejects.toThrow(/^Server does not support/); -}); - -test('should only allow setRequestHandler for declared capabilities', () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {} - } - } - ); - - // These should work because the capabilities are declared - expect(() => { - server.setRequestHandler(ListPromptsRequestSchema, () => ({ prompts: [] })); - }).not.toThrow(); - - expect(() => { - server.setRequestHandler(ListResourcesRequestSchema, () => ({ - resources: [] - })); - }).not.toThrow(); - - // These should throw because the capabilities are not declared - expect(() => { - server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [] })); - }).toThrow(/^Server does not support tools/); - - expect(() => { - server.setRequestHandler(SetLevelRequestSchema, () => ({})); - }).toThrow(/^Server does not support logging/); -}); - -/* - Test that custom request/notification/result schemas can be used with the Server class. - */ -test('should typecheck', () => { - const GetWeatherRequestSchema = RequestSchema.extend({ - method: z.literal('weather/get'), - params: z.object({ - city: z.string() - }) - }); - - const GetForecastRequestSchema = RequestSchema.extend({ - method: z.literal('weather/forecast'), - params: z.object({ - city: z.string(), - days: z.number() - }) - }); - - const WeatherForecastNotificationSchema = NotificationSchema.extend({ - method: z.literal('weather/alert'), - params: z.object({ - severity: z.enum(['warning', 'watch']), - message: z.string() - }) - }); - - const WeatherRequestSchema = GetWeatherRequestSchema.or(GetForecastRequestSchema); - const WeatherNotificationSchema = WeatherForecastNotificationSchema; - const WeatherResultSchema = ResultSchema.extend({ - temperature: z.number(), - conditions: z.string() - }); - - type WeatherRequest = z.infer; - type WeatherNotification = z.infer; - type WeatherResult = z.infer; - - // Create a typed Server for weather data - const weatherServer = new Server( - { - name: 'WeatherServer', - version: '1.0.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - } - } - ); - - // Typecheck that only valid weather requests/notifications/results are allowed - weatherServer.setRequestHandler(GetWeatherRequestSchema, _request => { - return { - temperature: 72, - conditions: 'sunny' - }; - }); - - weatherServer.setNotificationHandler(WeatherForecastNotificationSchema, notification => { - console.log(`Weather alert: ${notification.params.message}`); - }); -}); - -test('should handle server cancelling a request', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - // Set up client to delay responding to createMessage - client.setRequestHandler(CreateMessageRequestSchema, async (_request, _extra) => { - await new Promise(resolve => setTimeout(resolve, 1000)); - return { - model: 'test', - role: 'assistant', - content: { - type: 'text', - text: 'Test response' - } - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // Set up abort controller - const controller = new AbortController(); - - // Issue request but cancel it immediately - const createMessagePromise = server.createMessage( - { - messages: [], - maxTokens: 10 - }, - { - signal: controller.signal - } - ); - controller.abort('Cancelled by test'); - - // Request should be rejected - await expect(createMessagePromise).rejects.toBe('Cancelled by test'); -}); - -test('should handle request timeout', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - // Set up client that delays responses - const client = new Client( - { - name: 'test client', - version: '1.0' - }, - { - capabilities: { - sampling: {} - } - } - ); - - client.setRequestHandler(CreateMessageRequestSchema, async (_request, extra) => { - await new Promise((resolve, reject) => { - const timeout = setTimeout(resolve, 100); - extra.signal.addEventListener('abort', () => { - clearTimeout(timeout); - reject(extra.signal.reason); - }); - }); - - return { - model: 'test', - role: 'assistant', - content: { - type: 'text', - text: 'Test response' - } - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // Request with 0 msec timeout should fail immediately - await expect( - server.createMessage( - { - messages: [], - maxTokens: 10 - }, - { timeout: 0 } - ) - ).rejects.toMatchObject({ - code: ErrorCode.RequestTimeout - }); -}); - -/* - Test automatic log level handling for transports with and without sessionId - */ -test('should respect log level for transport without sessionId', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - }, - enforceStrictCapabilities: true - } - ); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - expect(clientTransport.sessionId).toEqual(undefined); - - // Client sets logging level to warning - await client.setLoggingLevel('warning'); - - // This one will make it through - const warningParams: LoggingMessageNotification['params'] = { - level: 'warning', - logger: 'test server', - data: 'Warning message' - }; - - // This one will not - const debugParams: LoggingMessageNotification['params'] = { - level: 'debug', - logger: 'test server', - data: 'Debug message' - }; - - // Test the one that makes it through - clientTransport.onmessage = jest.fn().mockImplementation(message => { - expect(message).toEqual({ - jsonrpc: '2.0', - method: 'notifications/message', - params: warningParams - }); - }); - - // This one will not make it through - await server.sendLoggingMessage(debugParams); - expect(clientTransport.onmessage).not.toHaveBeenCalled(); - - // This one will, triggering the above test in clientTransport.onmessage - await server.sendLoggingMessage(warningParams); - expect(clientTransport.onmessage).toHaveBeenCalled(); -}); - -test('should respect log level for transport with sessionId', async () => { - const server = new Server( - { - name: 'test server', - version: '1.0' - }, - { - capabilities: { - prompts: {}, - resources: {}, - tools: {}, - logging: {} - }, - enforceStrictCapabilities: true - } - ); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - // Add a session id to the transports - const SESSION_ID = 'test-session-id'; - clientTransport.sessionId = SESSION_ID; - serverTransport.sessionId = SESSION_ID; - - expect(clientTransport.sessionId).toBeDefined(); - expect(serverTransport.sessionId).toBeDefined(); - - await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); - - // Client sets logging level to warning - await client.setLoggingLevel('warning'); - - // This one will make it through - const warningParams: LoggingMessageNotification['params'] = { - level: 'warning', - logger: 'test server', - data: 'Warning message' - }; - - // This one will not - const debugParams: LoggingMessageNotification['params'] = { - level: 'debug', - logger: 'test server', - data: 'Debug message' - }; - - // Test the one that makes it through - clientTransport.onmessage = jest.fn().mockImplementation(message => { - expect(message).toEqual({ - jsonrpc: '2.0', - method: 'notifications/message', - params: warningParams - }); - }); - - // This one will not make it through - await server.sendLoggingMessage(debugParams, SESSION_ID); - expect(clientTransport.onmessage).not.toHaveBeenCalled(); - - // This one will, triggering the above test in clientTransport.onmessage - await server.sendLoggingMessage(warningParams, SESSION_ID); - expect(clientTransport.onmessage).toHaveBeenCalled(); -}); diff --git a/typescript-sdk/src/server/index.ts b/typescript-sdk/src/server/index.ts deleted file mode 100644 index c7f571f..0000000 --- a/typescript-sdk/src/server/index.ts +++ /dev/null @@ -1,390 +0,0 @@ -import { mergeCapabilities, Protocol, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; -import { - type ClientCapabilities, - type CreateMessageRequest, - CreateMessageResultSchema, - type ElicitRequest, - type ElicitResult, - ElicitResultSchema, - EmptyResultSchema, - ErrorCode, - type Implementation, - InitializedNotificationSchema, - type InitializeRequest, - InitializeRequestSchema, - type InitializeResult, - LATEST_PROTOCOL_VERSION, - type ListRootsRequest, - ListRootsResultSchema, - type LoggingLevel, - LoggingLevelSchema, - type LoggingMessageNotification, - McpError, - type Notification, - type Request, - type ResourceUpdatedNotification, - type Result, - type ServerCapabilities, - type ServerNotification, - type ServerRequest, - type ServerResult, - SetLevelRequestSchema, - SUPPORTED_PROTOCOL_VERSIONS -} from '../types.js'; -import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; -import type { JsonSchemaType, jsonSchemaValidator } from '../validation/types.js'; - -export type ServerOptions = ProtocolOptions & { - /** - * Capabilities to advertise as being supported by this server. - */ - capabilities?: ServerCapabilities; - - /** - * Optional instructions describing how to use the server and its features. - */ - instructions?: string; - - /** - * JSON Schema validator for elicitation response validation. - * - * The validator is used to validate user input returned from elicitation - * requests against the requested schema. - * - * @default AjvJsonSchemaValidator - * - * @example - * ```typescript - * // ajv (default) - * const server = new Server( - * { name: 'my-server', version: '1.0.0' }, - * { - * capabilities: {} - * jsonSchemaValidator: new AjvJsonSchemaValidator() - * } - * ); - * - * // @cfworker/json-schema - * const server = new Server( - * { name: 'my-server', version: '1.0.0' }, - * { - * capabilities: {}, - * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() - * } - * ); - * ``` - */ - jsonSchemaValidator?: jsonSchemaValidator; -}; - -/** - * An MCP server on top of a pluggable transport. - * - * This server will automatically respond to the initialization flow as initiated from the client. - * - * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: - * - * ```typescript - * // Custom schemas - * const CustomRequestSchema = RequestSchema.extend({...}) - * const CustomNotificationSchema = NotificationSchema.extend({...}) - * const CustomResultSchema = ResultSchema.extend({...}) - * - * // Type aliases - * type CustomRequest = z.infer - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed server - * const server = new Server({ - * name: "CustomServer", - * version: "1.0.0" - * }) - * ``` - */ -export class Server< - RequestT extends Request = Request, - NotificationT extends Notification = Notification, - ResultT extends Result = Result -> extends Protocol { - private _clientCapabilities?: ClientCapabilities; - private _clientVersion?: Implementation; - private _capabilities: ServerCapabilities; - private _instructions?: string; - private _jsonSchemaValidator: jsonSchemaValidator; - - /** - * Callback for when initialization has fully completed (i.e., the client has sent an `initialized` notification). - */ - oninitialized?: () => void; - - /** - * Initializes this server with the given name and version information. - */ - constructor( - private _serverInfo: Implementation, - options?: ServerOptions - ) { - super(options); - this._capabilities = options?.capabilities ?? {}; - this._instructions = options?.instructions; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - - this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request)); - this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); - - if (this._capabilities.logging) { - this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { - const transportSessionId: string | undefined = - extra.sessionId || (extra.requestInfo?.headers['mcp-session-id'] as string) || undefined; - const { level } = request.params; - const parseResult = LoggingLevelSchema.safeParse(level); - if (parseResult.success) { - this._loggingLevels.set(transportSessionId, parseResult.data); - } - return {}; - }); - } - } - - // Map log levels by session id - private _loggingLevels = new Map(); - - // Map LogLevelSchema to severity index - private readonly LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); - - // Is a message with the given level ignored in the log level set for the given session id? - private isMessageIgnored = (level: LoggingLevel, sessionId?: string): boolean => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level)! < this.LOG_LEVEL_SEVERITY.get(currentLevel)! : false; - }; - - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - public registerCapabilities(capabilities: ServerCapabilities): void { - if (this.transport) { - throw new Error('Cannot register capabilities after connecting to transport'); - } - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - } - - protected assertCapabilityForMethod(method: RequestT['method']): void { - switch (method as ServerRequest['method']) { - case 'sampling/createMessage': - if (!this._clientCapabilities?.sampling) { - throw new Error(`Client does not support sampling (required for ${method})`); - } - break; - - case 'elicitation/create': - if (!this._clientCapabilities?.elicitation) { - throw new Error(`Client does not support elicitation (required for ${method})`); - } - break; - - case 'roots/list': - if (!this._clientCapabilities?.roots) { - throw new Error(`Client does not support listing roots (required for ${method})`); - } - break; - - case 'ping': - // No specific capability required for ping - break; - } - } - - protected assertNotificationCapability(method: (ServerNotification | NotificationT)['method']): void { - switch (method as ServerNotification['method']) { - case 'notifications/message': - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - - case 'notifications/resources/updated': - case 'notifications/resources/list_changed': - if (!this._capabilities.resources) { - throw new Error(`Server does not support notifying about resources (required for ${method})`); - } - break; - - case 'notifications/tools/list_changed': - if (!this._capabilities.tools) { - throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); - } - break; - - case 'notifications/prompts/list_changed': - if (!this._capabilities.prompts) { - throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); - } - break; - - case 'notifications/cancelled': - // Cancellation notifications are always allowed - break; - - case 'notifications/progress': - // Progress notifications are always allowed - break; - } - } - - protected assertRequestHandlerCapability(method: string): void { - switch (method) { - case 'sampling/createMessage': - if (!this._capabilities.sampling) { - throw new Error(`Server does not support sampling (required for ${method})`); - } - break; - - case 'logging/setLevel': - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - - case 'prompts/get': - case 'prompts/list': - if (!this._capabilities.prompts) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - - case 'resources/list': - case 'resources/templates/list': - case 'resources/read': - if (!this._capabilities.resources) { - throw new Error(`Server does not support resources (required for ${method})`); - } - break; - - case 'tools/call': - case 'tools/list': - if (!this._capabilities.tools) { - throw new Error(`Server does not support tools (required for ${method})`); - } - break; - - case 'ping': - case 'initialize': - // No specific capability required for these methods - break; - } - } - - private async _oninitialize(request: InitializeRequest): Promise { - const requestedVersion = request.params.protocolVersion; - - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - - const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; - - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...(this._instructions && { instructions: this._instructions }) - }; - } - - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - */ - getClientCapabilities(): ClientCapabilities | undefined { - return this._clientCapabilities; - } - - /** - * After initialization has completed, this will be populated with information about the client's name and version. - */ - getClientVersion(): Implementation | undefined { - return this._clientVersion; - } - - private getCapabilities(): ServerCapabilities { - return this._capabilities; - } - - async ping() { - return this.request({ method: 'ping' }, EmptyResultSchema); - } - - async createMessage(params: CreateMessageRequest['params'], options?: RequestOptions) { - return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options); - } - - async elicitInput(params: ElicitRequest['params'], options?: RequestOptions): Promise { - const result = await this.request({ method: 'elicitation/create', params }, ElicitResultSchema, options); - - // Validate the response content against the requested schema if action is "accept" - if (result.action === 'accept' && result.content && params.requestedSchema) { - try { - const validator = this._jsonSchemaValidator.getValidator(params.requestedSchema as JsonSchemaType); - const validationResult = validator(result.content); - - if (!validationResult.valid) { - throw new McpError( - ErrorCode.InvalidParams, - `Elicitation response content does not match requested schema: ${validationResult.errorMessage}` - ); - } - } catch (error) { - if (error instanceof McpError) { - throw error; - } - throw new McpError( - ErrorCode.InternalError, - `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}` - ); - } - } - - return result; - } - - async listRoots(params?: ListRootsRequest['params'], options?: RequestOptions) { - return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options); - } - - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - async sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string) { - if (this._capabilities.logging) { - if (!this.isMessageIgnored(params.level, sessionId)) { - return this.notification({ method: 'notifications/message', params }); - } - } - } - - async sendResourceUpdated(params: ResourceUpdatedNotification['params']) { - return this.notification({ - method: 'notifications/resources/updated', - params - }); - } - - async sendResourceListChanged() { - return this.notification({ - method: 'notifications/resources/list_changed' - }); - } - - async sendToolListChanged() { - return this.notification({ method: 'notifications/tools/list_changed' }); - } - - async sendPromptListChanged() { - return this.notification({ method: 'notifications/prompts/list_changed' }); - } -} diff --git a/typescript-sdk/src/server/mcp.test.ts b/typescript-sdk/src/server/mcp.test.ts deleted file mode 100644 index 537bdc3..0000000 --- a/typescript-sdk/src/server/mcp.test.ts +++ /dev/null @@ -1,4122 +0,0 @@ -import { z } from 'zod'; -import { Client } from '../client/index.js'; -import { InMemoryTransport } from '../inMemory.js'; -import { getDisplayName } from '../shared/metadataUtils.js'; -import { UriTemplate } from '../shared/uriTemplate.js'; -import { - CallToolResultSchema, - CompleteResultSchema, - ElicitRequestSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ListToolsResultSchema, - LoggingMessageNotificationSchema, - type Notification, - ReadResourceResultSchema, - type TextContent -} from '../types.js'; -import { completable } from './completable.js'; -import { McpServer, ResourceTemplate } from './mcp.js'; - -describe('McpServer', () => { - /*** - * Test: Basic Server Instance - */ - test('should expose underlying Server instance', () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - expect(mcpServer.server).toBeDefined(); - }); - - /*** - * Test: Notification Sending via Server - */ - test('should allow sending notifications via Server', async () => { - const mcpServer = new McpServer( - { - name: 'test server', - version: '1.0' - }, - { capabilities: { logging: {} } } - ); - - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - // This should work because we're using the underlying server - await expect( - mcpServer.server.sendLoggingMessage({ - level: 'info', - data: 'Test log message' - }) - ).resolves.not.toThrow(); - - expect(notifications).toMatchObject([ - { - method: 'notifications/message', - params: { - level: 'info', - data: 'Test log message' - } - } - ]); - }); - - /*** - * Test: Progress Notification with Message Field - */ - test('should send progress notifications with message field', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - // Create a tool that sends progress updates - mcpServer.tool( - 'long-operation', - 'A long running operation with progress updates', - { - steps: z.number().min(1).describe('Number of steps to perform') - }, - async ({ steps }, { sendNotification, _meta }) => { - const progressToken = _meta?.progressToken; - - if (progressToken) { - // Send progress notification for each step - for (let i = 1; i <= steps; i++) { - await sendNotification({ - method: 'notifications/progress', - params: { - progressToken, - progress: i, - total: steps, - message: `Completed step ${i} of ${steps}` - } - }); - } - } - - return { - content: [ - { - type: 'text' as const, - text: `Operation completed with ${steps} steps` - } - ] - }; - } - ); - - const progressUpdates: Array<{ - progress: number; - total?: number; - message?: string; - }> = []; - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - // Call the tool with progress tracking - await client.request( - { - method: 'tools/call', - params: { - name: 'long-operation', - arguments: { steps: 3 }, - _meta: { - progressToken: 'progress-test-1' - } - } - }, - CallToolResultSchema, - { - onprogress: progress => { - progressUpdates.push(progress); - } - } - ); - - // Verify progress notifications were received with message field - expect(progressUpdates).toHaveLength(3); - expect(progressUpdates[0]).toMatchObject({ - progress: 1, - total: 3, - message: 'Completed step 1 of 3' - }); - expect(progressUpdates[1]).toMatchObject({ - progress: 2, - total: 3, - message: 'Completed step 2 of 3' - }); - expect(progressUpdates[2]).toMatchObject({ - progress: 3, - total: 3, - message: 'Completed step 3 of 3' - }); - }); -}); - -describe('ResourceTemplate', () => { - /*** - * Test: ResourceTemplate Creation with String Pattern - */ - test('should create ResourceTemplate with string pattern', () => { - const template = new ResourceTemplate('test://{category}/{id}', { - list: undefined - }); - expect(template.uriTemplate.toString()).toBe('test://{category}/{id}'); - expect(template.listCallback).toBeUndefined(); - }); - - /*** - * Test: ResourceTemplate Creation with UriTemplate Instance - */ - test('should create ResourceTemplate with UriTemplate', () => { - const uriTemplate = new UriTemplate('test://{category}/{id}'); - const template = new ResourceTemplate(uriTemplate, { list: undefined }); - expect(template.uriTemplate).toBe(uriTemplate); - expect(template.listCallback).toBeUndefined(); - }); - - /*** - * Test: ResourceTemplate with List Callback - */ - test('should create ResourceTemplate with list callback', async () => { - const list = jest.fn().mockResolvedValue({ - resources: [{ name: 'Test', uri: 'test://example' }] - }); - - const template = new ResourceTemplate('test://{id}', { list }); - expect(template.listCallback).toBe(list); - - const abortController = new AbortController(); - const result = await template.listCallback?.({ - signal: abortController.signal, - requestId: 'not-implemented', - sendRequest: () => { - throw new Error('Not implemented'); - }, - sendNotification: () => { - throw new Error('Not implemented'); - } - }); - expect(result?.resources).toHaveLength(1); - expect(list).toHaveBeenCalled(); - }); -}); - -describe('tool()', () => { - /*** - * Test: Zero-Argument Tool Registration - */ - test('should register zero-argument tool', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - mcpServer.tool('test', async () => ({ - content: [ - { - type: 'text', - text: 'Test response' - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - const result = await client.request( - { - method: 'tools/list' - }, - ListToolsResultSchema - ); - - expect(result.tools).toHaveLength(1); - expect(result.tools[0].name).toBe('test'); - expect(result.tools[0].inputSchema).toEqual({ - type: 'object', - properties: {} - }); - - // Adding the tool before the connection was established means no notification was sent - expect(notifications).toHaveLength(0); - - // Adding another tool triggers the update notification - mcpServer.tool('test2', async () => ({ - content: [ - { - type: 'text', - text: 'Test response' - } - ] - })); - - // Yield event loop to let the notification fly - await new Promise(process.nextTick); - - expect(notifications).toMatchObject([ - { - method: 'notifications/tools/list_changed' - } - ]); - }); - - /*** - * Test: Updating Existing Tool - */ - test('should update existing tool', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial tool - const tool = mcpServer.tool('test', async () => ({ - content: [ - { - type: 'text', - text: 'Initial response' - } - ] - })); - - // Update the tool - tool.update({ - callback: async () => ({ - content: [ - { - type: 'text', - text: 'Updated response' - } - ] - }) - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - // Call the tool and verify we get the updated response - const result = await client.request( - { - method: 'tools/call', - params: { - name: 'test' - } - }, - CallToolResultSchema - ); - - expect(result.content).toEqual([ - { - type: 'text', - text: 'Updated response' - } - ]); - - // Update happened before transport was connected, so no notifications should be expected - expect(notifications).toHaveLength(0); - }); - - /*** - * Test: Updating Tool with Schema - */ - test('should update tool with schema', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial tool - const tool = mcpServer.tool( - 'test', - { - name: z.string() - }, - async ({ name }) => ({ - content: [ - { - type: 'text', - text: `Initial: ${name}` - } - ] - }) - ); - - // Update the tool with a different schema - tool.update({ - paramsSchema: { - name: z.string(), - value: z.number() - }, - callback: async ({ name, value }) => ({ - content: [ - { - type: 'text', - text: `Updated: ${name}, ${value}` - } - ] - }) - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - // Verify the schema was updated - const listResult = await client.request( - { - method: 'tools/list' - }, - ListToolsResultSchema - ); - - expect(listResult.tools[0].inputSchema).toMatchObject({ - properties: { - name: { type: 'string' }, - value: { type: 'number' } - } - }); - - // Call the tool with the new schema - const callResult = await client.request( - { - method: 'tools/call', - params: { - name: 'test', - arguments: { - name: 'test', - value: 42 - } - } - }, - CallToolResultSchema - ); - - expect(callResult.content).toEqual([ - { - type: 'text', - text: 'Updated: test, 42' - } - ]); - - // Update happened before transport was connected, so no notifications should be expected - expect(notifications).toHaveLength(0); - }); - - /*** - * Test: Tool List Changed Notifications - */ - test('should send tool list changed notifications when connected', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial tool - const tool = mcpServer.tool('test', async () => ({ - content: [ - { - type: 'text', - text: 'Test response' - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - expect(notifications).toHaveLength(0); - - // Now update the tool - tool.update({ - callback: async () => ({ - content: [ - { - type: 'text', - text: 'Updated response' - } - ] - }) - }); - - // Yield event loop to let the notification fly - await new Promise(process.nextTick); - - expect(notifications).toMatchObject([{ method: 'notifications/tools/list_changed' }]); - - // Now delete the tool - tool.remove(); - - // Yield event loop to let the notification fly - await new Promise(process.nextTick); - - expect(notifications).toMatchObject([ - { method: 'notifications/tools/list_changed' }, - { method: 'notifications/tools/list_changed' } - ]); - }); - - /*** - * Test: Tool Registration with Parameters - */ - test('should register tool with params', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - // old api - mcpServer.tool( - 'test', - { - name: z.string(), - value: z.number() - }, - async ({ name, value }) => ({ - content: [ - { - type: 'text', - text: `${name}: ${value}` - } - ] - }) - ); - - // new api - mcpServer.registerTool( - 'test (new api)', - { - inputSchema: { name: z.string(), value: z.number() } - }, - async ({ name, value }) => ({ - content: [{ type: 'text', text: `${name}: ${value}` }] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'tools/list' - }, - ListToolsResultSchema - ); - - expect(result.tools).toHaveLength(2); - expect(result.tools[0].name).toBe('test'); - expect(result.tools[0].inputSchema).toMatchObject({ - type: 'object', - properties: { - name: { type: 'string' }, - value: { type: 'number' } - } - }); - expect(result.tools[1].name).toBe('test (new api)'); - expect(result.tools[1].inputSchema).toEqual(result.tools[0].inputSchema); - }); - - /*** - * Test: Tool Registration with Description - */ - test('should register tool with description', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - // old api - mcpServer.tool('test', 'Test description', async () => ({ - content: [ - { - type: 'text', - text: 'Test response' - } - ] - })); - - // new api - mcpServer.registerTool( - 'test (new api)', - { - description: 'Test description' - }, - async () => ({ - content: [ - { - type: 'text' as const, - text: 'Test response' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'tools/list' - }, - ListToolsResultSchema - ); - - expect(result.tools).toHaveLength(2); - expect(result.tools[0].name).toBe('test'); - expect(result.tools[0].description).toBe('Test description'); - expect(result.tools[1].name).toBe('test (new api)'); - expect(result.tools[1].description).toBe('Test description'); - }); - - /*** - * Test: Tool Registration with Annotations - */ - test('should register tool with annotations', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.tool('test', { title: 'Test Tool', readOnlyHint: true }, async () => ({ - content: [ - { - type: 'text', - text: 'Test response' - } - ] - })); - - mcpServer.registerTool( - 'test (new api)', - { - annotations: { title: 'Test Tool', readOnlyHint: true } - }, - async () => ({ - content: [ - { - type: 'text' as const, - text: 'Test response' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'tools/list' - }, - ListToolsResultSchema - ); - - expect(result.tools).toHaveLength(2); - expect(result.tools[0].name).toBe('test'); - expect(result.tools[0].annotations).toEqual({ - title: 'Test Tool', - readOnlyHint: true - }); - expect(result.tools[1].name).toBe('test (new api)'); - expect(result.tools[1].annotations).toEqual({ - title: 'Test Tool', - readOnlyHint: true - }); - }); - - /*** - * Test: Tool Registration with Parameters and Annotations - */ - test('should register tool with params and annotations', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.tool('test', { name: z.string() }, { title: 'Test Tool', readOnlyHint: true }, async ({ name }) => ({ - content: [{ type: 'text', text: `Hello, ${name}!` }] - })); - - mcpServer.registerTool( - 'test (new api)', - { - inputSchema: { name: z.string() }, - annotations: { title: 'Test Tool', readOnlyHint: true } - }, - async ({ name }) => ({ - content: [{ type: 'text', text: `Hello, ${name}!` }] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); - - expect(result.tools).toHaveLength(2); - expect(result.tools[0].name).toBe('test'); - expect(result.tools[0].inputSchema).toMatchObject({ - type: 'object', - properties: { name: { type: 'string' } } - }); - expect(result.tools[0].annotations).toEqual({ - title: 'Test Tool', - readOnlyHint: true - }); - expect(result.tools[1].name).toBe('test (new api)'); - expect(result.tools[1].inputSchema).toEqual(result.tools[0].inputSchema); - expect(result.tools[1].annotations).toEqual(result.tools[0].annotations); - }); - - /*** - * Test: Tool Registration with Description, Parameters, and Annotations - */ - test('should register tool with description, params, and annotations', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.tool( - 'test', - 'A tool with everything', - { name: z.string() }, - { title: 'Complete Test Tool', readOnlyHint: true, openWorldHint: false }, - async ({ name }) => ({ - content: [{ type: 'text', text: `Hello, ${name}!` }] - }) - ); - - mcpServer.registerTool( - 'test (new api)', - { - description: 'A tool with everything', - inputSchema: { name: z.string() }, - annotations: { - title: 'Complete Test Tool', - readOnlyHint: true, - openWorldHint: false - } - }, - async ({ name }) => ({ - content: [{ type: 'text', text: `Hello, ${name}!` }] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); - - expect(result.tools).toHaveLength(2); - expect(result.tools[0].name).toBe('test'); - expect(result.tools[0].description).toBe('A tool with everything'); - expect(result.tools[0].inputSchema).toMatchObject({ - type: 'object', - properties: { name: { type: 'string' } } - }); - expect(result.tools[0].annotations).toEqual({ - title: 'Complete Test Tool', - readOnlyHint: true, - openWorldHint: false - }); - expect(result.tools[1].name).toBe('test (new api)'); - expect(result.tools[1].description).toBe('A tool with everything'); - expect(result.tools[1].inputSchema).toEqual(result.tools[0].inputSchema); - expect(result.tools[1].annotations).toEqual(result.tools[0].annotations); - }); - - /*** - * Test: Tool Registration with Description, Empty Parameters, and Annotations - */ - test('should register tool with description, empty params, and annotations', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.tool( - 'test', - 'A tool with everything but empty params', - {}, - { - title: 'Complete Test Tool with empty params', - readOnlyHint: true, - openWorldHint: false - }, - async () => ({ - content: [{ type: 'text', text: 'Test response' }] - }) - ); - - mcpServer.registerTool( - 'test (new api)', - { - description: 'A tool with everything but empty params', - inputSchema: {}, - annotations: { - title: 'Complete Test Tool with empty params', - readOnlyHint: true, - openWorldHint: false - } - }, - async () => ({ - content: [{ type: 'text' as const, text: 'Test response' }] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); - - expect(result.tools).toHaveLength(2); - expect(result.tools[0].name).toBe('test'); - expect(result.tools[0].description).toBe('A tool with everything but empty params'); - expect(result.tools[0].inputSchema).toMatchObject({ - type: 'object', - properties: {} - }); - expect(result.tools[0].annotations).toEqual({ - title: 'Complete Test Tool with empty params', - readOnlyHint: true, - openWorldHint: false - }); - expect(result.tools[1].name).toBe('test (new api)'); - expect(result.tools[1].description).toBe('A tool with everything but empty params'); - expect(result.tools[1].inputSchema).toEqual(result.tools[0].inputSchema); - expect(result.tools[1].annotations).toEqual(result.tools[0].annotations); - }); - - /*** - * Test: Tool Argument Validation - */ - test('should validate tool args', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.tool( - 'test', - { - name: z.string(), - value: z.number() - }, - async ({ name, value }) => ({ - content: [ - { - type: 'text', - text: `${name}: ${value}` - } - ] - }) - ); - - mcpServer.registerTool( - 'test (new api)', - { - inputSchema: { - name: z.string(), - value: z.number() - } - }, - async ({ name, value }) => ({ - content: [ - { - type: 'text', - text: `${name}: ${value}` - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - await expect( - client.request( - { - method: 'tools/call', - params: { - name: 'test', - arguments: { - name: 'test', - value: 'not a number' - } - } - }, - CallToolResultSchema - ) - ).rejects.toThrow(/Invalid arguments/); - - await expect( - client.request( - { - method: 'tools/call', - params: { - name: 'test (new api)', - arguments: { - name: 'test', - value: 'not a number' - } - } - }, - CallToolResultSchema - ) - ).rejects.toThrow(/Invalid arguments/); - }); - - /*** - * Test: Preventing Duplicate Tool Registration - */ - test('should prevent duplicate tool registration', () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - mcpServer.tool('test', async () => ({ - content: [ - { - type: 'text', - text: 'Test response' - } - ] - })); - - expect(() => { - mcpServer.tool('test', async () => ({ - content: [ - { - type: 'text', - text: 'Test response 2' - } - ] - })); - }).toThrow(/already registered/); - }); - - /*** - * Test: Multiple Tool Registration - */ - test('should allow registering multiple tools', () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - // This should succeed - mcpServer.tool('tool1', () => ({ content: [] })); - - // This should also succeed and not throw about request handlers - mcpServer.tool('tool2', () => ({ content: [] })); - }); - - /*** - * Test: Tool with Output Schema and Structured Content - */ - test('should support tool with outputSchema and structuredContent', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - // Register a tool with outputSchema - mcpServer.registerTool( - 'test', - { - description: 'Test tool with structured output', - inputSchema: { - input: z.string() - }, - outputSchema: { - processedInput: z.string(), - resultType: z.string(), - timestamp: z.string() - } - }, - async ({ input }) => ({ - structuredContent: { - processedInput: input, - resultType: 'structured', - timestamp: '2023-01-01T00:00:00Z' - }, - content: [ - { - type: 'text', - text: JSON.stringify({ - processedInput: input, - resultType: 'structured', - timestamp: '2023-01-01T00:00:00Z' - }) - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - // Verify the tool registration includes outputSchema - const listResult = await client.request( - { - method: 'tools/list' - }, - ListToolsResultSchema - ); - - expect(listResult.tools).toHaveLength(1); - expect(listResult.tools[0].outputSchema).toMatchObject({ - type: 'object', - properties: { - processedInput: { type: 'string' }, - resultType: { type: 'string' }, - timestamp: { type: 'string' } - }, - required: ['processedInput', 'resultType', 'timestamp'] - }); - - // Call the tool and verify it returns valid structuredContent - const result = await client.request( - { - method: 'tools/call', - params: { - name: 'test', - arguments: { - input: 'hello' - } - } - }, - CallToolResultSchema - ); - - expect(result.structuredContent).toBeDefined(); - const structuredContent = result.structuredContent as { - processedInput: string; - resultType: string; - timestamp: string; - }; - expect(structuredContent.processedInput).toBe('hello'); - expect(structuredContent.resultType).toBe('structured'); - expect(structuredContent.timestamp).toBe('2023-01-01T00:00:00Z'); - - // For backward compatibility, content is auto-generated from structuredContent - expect(result.content).toBeDefined(); - expect(result.content!).toHaveLength(1); - expect(result.content![0]).toMatchObject({ type: 'text' }); - const textContent = result.content![0] as TextContent; - expect(JSON.parse(textContent.text)).toEqual(result.structuredContent); - }); - - /*** - * Test: Tool with Output Schema Must Provide Structured Content - */ - test('should throw error when tool with outputSchema returns no structuredContent', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - // Register a tool with outputSchema that returns only content without structuredContent - mcpServer.registerTool( - 'test', - { - description: 'Test tool with output schema but missing structured content', - inputSchema: { - input: z.string() - }, - outputSchema: { - processedInput: z.string(), - resultType: z.string() - } - }, - async ({ input }) => ({ - // Only return content without structuredContent - content: [ - { - type: 'text', - text: `Processed: ${input}` - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - // Call the tool and expect it to throw an error - await expect( - client.callTool({ - name: 'test', - arguments: { - input: 'hello' - } - }) - ).rejects.toThrow(/Tool test has an output schema but no structured content was provided/); - }); - /*** - * Test: Tool with Output Schema Must Provide Structured Content - */ - test('should skip outputSchema validation when isError is true', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.registerTool( - 'test', - { - description: 'Test tool with output schema but missing structured content', - inputSchema: { - input: z.string() - }, - outputSchema: { - processedInput: z.string(), - resultType: z.string() - } - }, - async ({ input }) => ({ - content: [ - { - type: 'text', - text: `Processed: ${input}` - } - ], - isError: true - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - await expect( - client.callTool({ - name: 'test', - arguments: { - input: 'hello' - } - }) - ).resolves.toStrictEqual({ - content: [ - { - type: 'text', - text: `Processed: hello` - } - ], - isError: true - }); - }); - - /*** - * Test: Schema Validation Failure for Invalid Structured Content - */ - test('should fail schema validation when tool returns invalid structuredContent', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - // Register a tool with outputSchema that returns invalid data - mcpServer.registerTool( - 'test', - { - description: 'Test tool with invalid structured output', - inputSchema: { - input: z.string() - }, - outputSchema: { - processedInput: z.string(), - resultType: z.string(), - timestamp: z.string() - } - }, - async ({ input }) => ({ - content: [ - { - type: 'text', - text: JSON.stringify({ - processedInput: input, - resultType: 'structured', - // Missing required 'timestamp' field - someExtraField: 'unexpected' // Extra field not in schema - }) - } - ], - structuredContent: { - processedInput: input, - resultType: 'structured', - // Missing required 'timestamp' field - someExtraField: 'unexpected' // Extra field not in schema - } - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - // Call the tool and expect it to throw a server-side validation error - await expect( - client.callTool({ - name: 'test', - arguments: { - input: 'hello' - } - }) - ).rejects.toThrow(/Invalid structured content for tool test/); - }); - - /*** - * Test: Pass Session ID to Tool Callback - */ - test('should pass sessionId to tool callback via RequestHandlerExtra', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - let receivedSessionId: string | undefined; - mcpServer.tool('test-tool', async extra => { - receivedSessionId = extra.sessionId; - return { - content: [ - { - type: 'text', - text: 'Test response' - } - ] - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - // Set a test sessionId on the server transport - serverTransport.sessionId = 'test-session-123'; - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - await client.request( - { - method: 'tools/call', - params: { - name: 'test-tool' - } - }, - CallToolResultSchema - ); - - expect(receivedSessionId).toBe('test-session-123'); - }); - - /*** - * Test: Pass Request ID to Tool Callback - */ - test('should pass requestId to tool callback via RequestHandlerExtra', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - let receivedRequestId: string | number | undefined; - mcpServer.tool('request-id-test', async extra => { - receivedRequestId = extra.requestId; - return { - content: [ - { - type: 'text', - text: `Received request ID: ${extra.requestId}` - } - ] - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'tools/call', - params: { - name: 'request-id-test' - } - }, - CallToolResultSchema - ); - - expect(receivedRequestId).toBeDefined(); - expect(typeof receivedRequestId === 'string' || typeof receivedRequestId === 'number').toBe(true); - expect(result.content?.[0].text).toContain('Received request ID:'); - }); - - /*** - * Test: Send Notification within Tool Call - */ - test('should provide sendNotification within tool call', async () => { - const mcpServer = new McpServer( - { - name: 'test server', - version: '1.0' - }, - { capabilities: { logging: {} } } - ); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - let receivedLogMessage: string | undefined; - const loggingMessage = 'hello here is log message 1'; - - client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - receivedLogMessage = notification.params.data as string; - }); - - mcpServer.tool('test-tool', async ({ sendNotification }) => { - await sendNotification({ - method: 'notifications/message', - params: { level: 'debug', data: loggingMessage } - }); - return { - content: [ - { - type: 'text', - text: 'Test response' - } - ] - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - await client.request( - { - method: 'tools/call', - params: { - name: 'test-tool' - } - }, - CallToolResultSchema - ); - expect(receivedLogMessage).toBe(loggingMessage); - }); - - /*** - * Test: Client to Server Tool Call - */ - test('should allow client to call server tools', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.tool( - 'test', - 'Test tool', - { - input: z.string() - }, - async ({ input }) => ({ - content: [ - { - type: 'text', - text: `Processed: ${input}` - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'tools/call', - params: { - name: 'test', - arguments: { - input: 'hello' - } - } - }, - CallToolResultSchema - ); - - expect(result.content).toEqual([ - { - type: 'text', - text: 'Processed: hello' - } - ]); - }); - - /*** - * Test: Graceful Tool Error Handling - */ - test('should handle server tool errors gracefully', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.tool('error-test', async () => { - throw new Error('Tool execution failed'); - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'tools/call', - params: { - name: 'error-test' - } - }, - CallToolResultSchema - ); - - expect(result.isError).toBe(true); - expect(result.content).toEqual([ - { - type: 'text', - text: 'Tool execution failed' - } - ]); - }); - - /*** - * Test: McpError for Invalid Tool Name - */ - test('should throw McpError for invalid tool name', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.tool('test-tool', async () => ({ - content: [ - { - type: 'text', - text: 'Test response' - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - await expect( - client.request( - { - method: 'tools/call', - params: { - name: 'nonexistent-tool' - } - }, - CallToolResultSchema - ) - ).rejects.toThrow(/Tool nonexistent-tool not found/); - }); - - /*** - * Test: Tool Registration with _meta field - */ - test('should register tool with _meta field and include it in list response', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - const metaData = { - author: 'test-author', - version: '1.2.3', - category: 'utility', - tags: ['test', 'example'] - }; - - mcpServer.registerTool( - 'test-with-meta', - { - description: 'A tool with _meta field', - inputSchema: { name: z.string() }, - _meta: metaData - }, - async ({ name }) => ({ - content: [{ type: 'text', text: `Hello, ${name}!` }] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); - - expect(result.tools).toHaveLength(1); - expect(result.tools[0].name).toBe('test-with-meta'); - expect(result.tools[0].description).toBe('A tool with _meta field'); - expect(result.tools[0]._meta).toEqual(metaData); - }); - - /*** - * Test: Tool Registration without _meta field should have undefined _meta - */ - test('should register tool without _meta field and have undefined _meta in response', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.registerTool( - 'test-without-meta', - { - description: 'A tool without _meta field', - inputSchema: { name: z.string() } - }, - async ({ name }) => ({ - content: [{ type: 'text', text: `Hello, ${name}!` }] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); - - expect(result.tools).toHaveLength(1); - expect(result.tools[0].name).toBe('test-without-meta'); - expect(result.tools[0]._meta).toBeUndefined(); - }); -}); - -describe('resource()', () => { - /*** - * Test: Resource Registration with URI and Read Callback - */ - test('should register resource with uri and readCallback', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource('test', 'test://resource', async () => ({ - contents: [ - { - uri: 'test://resource', - text: 'Test content' - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'resources/list' - }, - ListResourcesResultSchema - ); - - expect(result.resources).toHaveLength(1); - expect(result.resources[0].name).toBe('test'); - expect(result.resources[0].uri).toBe('test://resource'); - }); - - /*** - * Test: Update Resource with URI - */ - test('should update resource with uri', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial resource - const resource = mcpServer.resource('test', 'test://resource', async () => ({ - contents: [ - { - uri: 'test://resource', - text: 'Initial content' - } - ] - })); - - // Update the resource - resource.update({ - callback: async () => ({ - contents: [ - { - uri: 'test://resource', - text: 'Updated content' - } - ] - }) - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - // Read the resource and verify we get the updated content - const result = await client.request( - { - method: 'resources/read', - params: { - uri: 'test://resource' - } - }, - ReadResourceResultSchema - ); - - expect(result.contents).toHaveLength(1); - expect(result.contents[0].text).toBe('Updated content'); - - // Update happened before transport was connected, so no notifications should be expected - expect(notifications).toHaveLength(0); - }); - - /*** - * Test: Update Resource Template - */ - test('should update resource template', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial resource template - const resourceTemplate = mcpServer.resource( - 'test', - new ResourceTemplate('test://resource/{id}', { list: undefined }), - async uri => ({ - contents: [ - { - uri: uri.href, - text: 'Initial content' - } - ] - }) - ); - - // Update the resource template - resourceTemplate.update({ - callback: async uri => ({ - contents: [ - { - uri: uri.href, - text: 'Updated content' - } - ] - }) - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - // Read the resource and verify we get the updated content - const result = await client.request( - { - method: 'resources/read', - params: { - uri: 'test://resource/123' - } - }, - ReadResourceResultSchema - ); - - expect(result.contents).toHaveLength(1); - expect(result.contents[0].text).toBe('Updated content'); - - // Update happened before transport was connected, so no notifications should be expected - expect(notifications).toHaveLength(0); - }); - - /*** - * Test: Resource List Changed Notification - */ - test('should send resource list changed notification when connected', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial resource - const resource = mcpServer.resource('test', 'test://resource', async () => ({ - contents: [ - { - uri: 'test://resource', - text: 'Test content' - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - expect(notifications).toHaveLength(0); - - // Now update the resource while connected - resource.update({ - callback: async () => ({ - contents: [ - { - uri: 'test://resource', - text: 'Updated content' - } - ] - }) - }); - - // Yield event loop to let the notification fly - await new Promise(process.nextTick); - - expect(notifications).toMatchObject([{ method: 'notifications/resources/list_changed' }]); - }); - - /*** - * Test: Remove Resource and Send Notification - */ - test('should remove resource and send notification when connected', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial resources - const resource1 = mcpServer.resource('resource1', 'test://resource1', async () => ({ - contents: [{ uri: 'test://resource1', text: 'Resource 1 content' }] - })); - - mcpServer.resource('resource2', 'test://resource2', async () => ({ - contents: [{ uri: 'test://resource2', text: 'Resource 2 content' }] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - // Verify both resources are registered - let result = await client.request({ method: 'resources/list' }, ListResourcesResultSchema); - - expect(result.resources).toHaveLength(2); - - expect(notifications).toHaveLength(0); - - // Remove a resource - resource1.remove(); - - // Yield event loop to let the notification fly - await new Promise(process.nextTick); - - // Should have sent notification - expect(notifications).toMatchObject([{ method: 'notifications/resources/list_changed' }]); - - // Verify the resource was removed - result = await client.request({ method: 'resources/list' }, ListResourcesResultSchema); - - expect(result.resources).toHaveLength(1); - expect(result.resources[0].uri).toBe('test://resource2'); - }); - - /*** - * Test: Remove Resource Template and Send Notification - */ - test('should remove resource template and send notification when connected', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register resource template - const resourceTemplate = mcpServer.resource( - 'template', - new ResourceTemplate('test://resource/{id}', { list: undefined }), - async uri => ({ - contents: [ - { - uri: uri.href, - text: 'Template content' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - // Verify template is registered - const result = await client.request({ method: 'resources/templates/list' }, ListResourceTemplatesResultSchema); - - expect(result.resourceTemplates).toHaveLength(1); - expect(notifications).toHaveLength(0); - - // Remove the template - resourceTemplate.remove(); - - // Yield event loop to let the notification fly - await new Promise(process.nextTick); - - // Should have sent notification - expect(notifications).toMatchObject([{ method: 'notifications/resources/list_changed' }]); - - // Verify the template was removed - const result2 = await client.request({ method: 'resources/templates/list' }, ListResourceTemplatesResultSchema); - - expect(result2.resourceTemplates).toHaveLength(0); - }); - - /*** - * Test: Resource Registration with Metadata - */ - test('should register resource with metadata', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource( - 'test', - 'test://resource', - { - description: 'Test resource', - mimeType: 'text/plain' - }, - async () => ({ - contents: [ - { - uri: 'test://resource', - text: 'Test content' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'resources/list' - }, - ListResourcesResultSchema - ); - - expect(result.resources).toHaveLength(1); - expect(result.resources[0].description).toBe('Test resource'); - expect(result.resources[0].mimeType).toBe('text/plain'); - }); - - /*** - * Test: Resource Template Registration - */ - test('should register resource template', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource('test', new ResourceTemplate('test://resource/{id}', { list: undefined }), async () => ({ - contents: [ - { - uri: 'test://resource/123', - text: 'Test content' - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'resources/templates/list' - }, - ListResourceTemplatesResultSchema - ); - - expect(result.resourceTemplates).toHaveLength(1); - expect(result.resourceTemplates[0].name).toBe('test'); - expect(result.resourceTemplates[0].uriTemplate).toBe('test://resource/{id}'); - }); - - /*** - * Test: Resource Template with List Callback - */ - test('should register resource template with listCallback', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource( - 'test', - new ResourceTemplate('test://resource/{id}', { - list: async () => ({ - resources: [ - { - name: 'Resource 1', - uri: 'test://resource/1' - }, - { - name: 'Resource 2', - uri: 'test://resource/2' - } - ] - }) - }), - async uri => ({ - contents: [ - { - uri: uri.href, - text: 'Test content' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'resources/list' - }, - ListResourcesResultSchema - ); - - expect(result.resources).toHaveLength(2); - expect(result.resources[0].name).toBe('Resource 1'); - expect(result.resources[0].uri).toBe('test://resource/1'); - expect(result.resources[1].name).toBe('Resource 2'); - expect(result.resources[1].uri).toBe('test://resource/2'); - }); - - /*** - * Test: Template Variables to Read Callback - */ - test('should pass template variables to readCallback', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource( - 'test', - new ResourceTemplate('test://resource/{category}/{id}', { - list: undefined - }), - async (uri, { category, id }) => ({ - contents: [ - { - uri: uri.href, - text: `Category: ${category}, ID: ${id}` - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'resources/read', - params: { - uri: 'test://resource/books/123' - } - }, - ReadResourceResultSchema - ); - - expect(result.contents[0].text).toBe('Category: books, ID: 123'); - }); - - /*** - * Test: Preventing Duplicate Resource Registration - */ - test('should prevent duplicate resource registration', () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - mcpServer.resource('test', 'test://resource', async () => ({ - contents: [ - { - uri: 'test://resource', - text: 'Test content' - } - ] - })); - - expect(() => { - mcpServer.resource('test2', 'test://resource', async () => ({ - contents: [ - { - uri: 'test://resource', - text: 'Test content 2' - } - ] - })); - }).toThrow(/already registered/); - }); - - /*** - * Test: Multiple Resource Registration - */ - test('should allow registering multiple resources', () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - // This should succeed - mcpServer.resource('resource1', 'test://resource1', async () => ({ - contents: [ - { - uri: 'test://resource1', - text: 'Test content 1' - } - ] - })); - - // This should also succeed and not throw about request handlers - mcpServer.resource('resource2', 'test://resource2', async () => ({ - contents: [ - { - uri: 'test://resource2', - text: 'Test content 2' - } - ] - })); - }); - - /*** - * Test: Preventing Duplicate Resource Template Registration - */ - test('should prevent duplicate resource template registration', () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - mcpServer.resource('test', new ResourceTemplate('test://resource/{id}', { list: undefined }), async () => ({ - contents: [ - { - uri: 'test://resource/123', - text: 'Test content' - } - ] - })); - - expect(() => { - mcpServer.resource('test', new ResourceTemplate('test://resource/{id}', { list: undefined }), async () => ({ - contents: [ - { - uri: 'test://resource/123', - text: 'Test content 2' - } - ] - })); - }).toThrow(/already registered/); - }); - - /*** - * Test: Graceful Resource Read Error Handling - */ - test('should handle resource read errors gracefully', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource('error-test', 'test://error', async () => { - throw new Error('Resource read failed'); - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - await expect( - client.request( - { - method: 'resources/read', - params: { - uri: 'test://error' - } - }, - ReadResourceResultSchema - ) - ).rejects.toThrow(/Resource read failed/); - }); - - /*** - * Test: McpError for Invalid Resource URI - */ - test('should throw McpError for invalid resource URI', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource('test', 'test://resource', async () => ({ - contents: [ - { - uri: 'test://resource', - text: 'Test content' - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - await expect( - client.request( - { - method: 'resources/read', - params: { - uri: 'test://nonexistent' - } - }, - ReadResourceResultSchema - ) - ).rejects.toThrow(/Resource test:\/\/nonexistent not found/); - }); - - /*** - * Test: Registering a resource template with a complete callback should update server capabilities to advertise support for completion - */ - test('should advertise support for completion when a resource template with a complete callback is defined', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource( - 'test', - new ResourceTemplate('test://resource/{category}', { - list: undefined, - complete: { - category: () => ['books', 'movies', 'music'] - } - }), - async () => ({ - contents: [ - { - uri: 'test://resource/test', - text: 'Test content' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - expect(client.getServerCapabilities()).toMatchObject({ completions: {} }); - }); - - /*** - * Test: Resource Template Parameter Completion - */ - test('should support completion of resource template parameters', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource( - 'test', - new ResourceTemplate('test://resource/{category}', { - list: undefined, - complete: { - category: () => ['books', 'movies', 'music'] - } - }), - async () => ({ - contents: [ - { - uri: 'test://resource/test', - text: 'Test content' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/resource', - uri: 'test://resource/{category}' - }, - argument: { - name: 'category', - value: '' - } - } - }, - CompleteResultSchema - ); - - expect(result.completion.values).toEqual(['books', 'movies', 'music']); - expect(result.completion.total).toBe(3); - }); - - /*** - * Test: Filtered Resource Template Parameter Completion - */ - test('should support filtered completion of resource template parameters', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource( - 'test', - new ResourceTemplate('test://resource/{category}', { - list: undefined, - complete: { - category: (test: string) => ['books', 'movies', 'music'].filter(value => value.startsWith(test)) - } - }), - async () => ({ - contents: [ - { - uri: 'test://resource/test', - text: 'Test content' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/resource', - uri: 'test://resource/{category}' - }, - argument: { - name: 'category', - value: 'm' - } - } - }, - CompleteResultSchema - ); - - expect(result.completion.values).toEqual(['movies', 'music']); - expect(result.completion.total).toBe(2); - }); - - /*** - * Test: Pass Request ID to Resource Callback - */ - test('should pass requestId to resource callback via RequestHandlerExtra', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - let receivedRequestId: string | number | undefined; - mcpServer.resource('request-id-test', 'test://resource', async (_uri, extra) => { - receivedRequestId = extra.requestId; - return { - contents: [ - { - uri: 'test://resource', - text: `Received request ID: ${extra.requestId}` - } - ] - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'resources/read', - params: { - uri: 'test://resource' - } - }, - ReadResourceResultSchema - ); - - expect(receivedRequestId).toBeDefined(); - expect(typeof receivedRequestId === 'string' || typeof receivedRequestId === 'number').toBe(true); - expect(result.contents[0].text).toContain('Received request ID:'); - }); -}); - -describe('prompt()', () => { - /*** - * Test: Zero-Argument Prompt Registration - */ - test('should register zero-argument prompt', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.prompt('test', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Test response' - } - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'prompts/list' - }, - ListPromptsResultSchema - ); - - expect(result.prompts).toHaveLength(1); - expect(result.prompts[0].name).toBe('test'); - expect(result.prompts[0].arguments).toBeUndefined(); - }); - /*** - * Test: Updating Existing Prompt - */ - test('should update existing prompt', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial prompt - const prompt = mcpServer.prompt('test', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Initial response' - } - } - ] - })); - - // Update the prompt - prompt.update({ - callback: async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Updated response' - } - } - ] - }) - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - // Call the prompt and verify we get the updated response - const result = await client.request( - { - method: 'prompts/get', - params: { - name: 'test' - } - }, - GetPromptResultSchema - ); - - expect(result.messages).toHaveLength(1); - expect(result.messages[0].content.text).toBe('Updated response'); - - // Update happened before transport was connected, so no notifications should be expected - expect(notifications).toHaveLength(0); - }); - - /*** - * Test: Updating Prompt with Schema - */ - test('should update prompt with schema', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial prompt - const prompt = mcpServer.prompt( - 'test', - { - name: z.string() - }, - async ({ name }) => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `Initial: ${name}` - } - } - ] - }) - ); - - // Update the prompt with a different schema - prompt.update({ - argsSchema: { - name: z.string(), - value: z.string() - }, - callback: async ({ name, value }) => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `Updated: ${name}, ${value}` - } - } - ] - }) - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - // Verify the schema was updated - const listResult = await client.request( - { - method: 'prompts/list' - }, - ListPromptsResultSchema - ); - - expect(listResult.prompts[0].arguments).toHaveLength(2); - expect(listResult.prompts[0].arguments?.map(a => a.name).sort()).toEqual(['name', 'value']); - - // Call the prompt with the new schema - const getResult = await client.request( - { - method: 'prompts/get', - params: { - name: 'test', - arguments: { - name: 'test', - value: 'value' - } - } - }, - GetPromptResultSchema - ); - - expect(getResult.messages).toHaveLength(1); - expect(getResult.messages[0].content.text).toBe('Updated: test, value'); - - // Update happened before transport was connected, so no notifications should be expected - expect(notifications).toHaveLength(0); - }); - - /*** - * Test: Prompt List Changed Notification - */ - test('should send prompt list changed notification when connected', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial prompt - const prompt = mcpServer.prompt('test', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Test response' - } - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - expect(notifications).toHaveLength(0); - - // Now update the prompt while connected - prompt.update({ - callback: async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Updated response' - } - } - ] - }) - }); - - // Yield event loop to let the notification fly - await new Promise(process.nextTick); - - expect(notifications).toMatchObject([{ method: 'notifications/prompts/list_changed' }]); - }); - - /*** - * Test: Remove Prompt and Send Notification - */ - test('should remove prompt and send notification when connected', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const notifications: Notification[] = []; - const client = new Client({ - name: 'test client', - version: '1.0' - }); - client.fallbackNotificationHandler = async notification => { - notifications.push(notification); - }; - - // Register initial prompts - const prompt1 = mcpServer.prompt('prompt1', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Prompt 1 response' - } - } - ] - })); - - mcpServer.prompt('prompt2', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Prompt 2 response' - } - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - // Verify both prompts are registered - let result = await client.request({ method: 'prompts/list' }, ListPromptsResultSchema); - - expect(result.prompts).toHaveLength(2); - expect(result.prompts.map(p => p.name).sort()).toEqual(['prompt1', 'prompt2']); - - expect(notifications).toHaveLength(0); - - // Remove a prompt - prompt1.remove(); - - // Yield event loop to let the notification fly - await new Promise(process.nextTick); - - // Should have sent notification - expect(notifications).toMatchObject([{ method: 'notifications/prompts/list_changed' }]); - - // Verify the prompt was removed - result = await client.request({ method: 'prompts/list' }, ListPromptsResultSchema); - - expect(result.prompts).toHaveLength(1); - expect(result.prompts[0].name).toBe('prompt2'); - }); - - /*** - * Test: Prompt Registration with Arguments Schema - */ - test('should register prompt with args schema', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.prompt( - 'test', - { - name: z.string(), - value: z.string() - }, - async ({ name, value }) => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `${name}: ${value}` - } - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'prompts/list' - }, - ListPromptsResultSchema - ); - - expect(result.prompts).toHaveLength(1); - expect(result.prompts[0].name).toBe('test'); - expect(result.prompts[0].arguments).toEqual([ - { name: 'name', required: true }, - { name: 'value', required: true } - ]); - }); - - /*** - * Test: Prompt Registration with Description - */ - test('should register prompt with description', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.prompt('test', 'Test description', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Test response' - } - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'prompts/list' - }, - ListPromptsResultSchema - ); - - expect(result.prompts).toHaveLength(1); - expect(result.prompts[0].name).toBe('test'); - expect(result.prompts[0].description).toBe('Test description'); - }); - - /*** - * Test: Prompt Argument Validation - */ - test('should validate prompt args', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.prompt( - 'test', - { - name: z.string(), - value: z.string().min(3) - }, - async ({ name, value }) => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `${name}: ${value}` - } - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - await expect( - client.request( - { - method: 'prompts/get', - params: { - name: 'test', - arguments: { - name: 'test', - value: 'ab' // Too short - } - } - }, - GetPromptResultSchema - ) - ).rejects.toThrow(/Invalid arguments/); - }); - - /*** - * Test: Preventing Duplicate Prompt Registration - */ - test('should prevent duplicate prompt registration', () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - mcpServer.prompt('test', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Test response' - } - } - ] - })); - - expect(() => { - mcpServer.prompt('test', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Test response 2' - } - } - ] - })); - }).toThrow(/already registered/); - }); - - /*** - * Test: Multiple Prompt Registration - */ - test('should allow registering multiple prompts', () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - // This should succeed - mcpServer.prompt('prompt1', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Test response 1' - } - } - ] - })); - - // This should also succeed and not throw about request handlers - mcpServer.prompt('prompt2', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Test response 2' - } - } - ] - })); - }); - - /*** - * Test: Prompt Registration with Arguments - */ - test('should allow registering prompts with arguments', () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - // This should succeed - mcpServer.prompt('echo', { message: z.string() }, ({ message }) => ({ - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please process this message: ${message}` - } - } - ] - })); - }); - - /*** - * Test: Resources and Prompts with Completion Handlers - */ - test('should allow registering both resources and prompts with completion handlers', () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - // Register a resource with completion - mcpServer.resource( - 'test', - new ResourceTemplate('test://resource/{category}', { - list: undefined, - complete: { - category: () => ['books', 'movies', 'music'] - } - }), - async () => ({ - contents: [ - { - uri: 'test://resource/test', - text: 'Test content' - } - ] - }) - ); - - // Register a prompt with completion - mcpServer.prompt('echo', { message: completable(z.string(), () => ['hello', 'world']) }, ({ message }) => ({ - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please process this message: ${message}` - } - } - ] - })); - }); - - /*** - * Test: McpError for Invalid Prompt Name - */ - test('should throw McpError for invalid prompt name', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.prompt('test-prompt', async () => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: 'Test response' - } - } - ] - })); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - await expect( - client.request( - { - method: 'prompts/get', - params: { - name: 'nonexistent-prompt' - } - }, - GetPromptResultSchema - ) - ).rejects.toThrow(/Prompt nonexistent-prompt not found/); - }); - - /*** - * Test: Registering a prompt with a completable argument should update server capabilities to advertise support for completion - */ - test('should advertise support for completion when a prompt with a completable argument is defined', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.prompt( - 'test-prompt', - { - name: completable(z.string(), () => ['Alice', 'Bob', 'Charlie']) - }, - async ({ name }) => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `Hello ${name}` - } - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - expect(client.getServerCapabilities()).toMatchObject({ completions: {} }); - }); - - /*** - * Test: Prompt Argument Completion - */ - test('should support completion of prompt arguments', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.prompt( - 'test-prompt', - { - name: completable(z.string(), () => ['Alice', 'Bob', 'Charlie']) - }, - async ({ name }) => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `Hello ${name}` - } - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/prompt', - name: 'test-prompt' - }, - argument: { - name: 'name', - value: '' - } - } - }, - CompleteResultSchema - ); - - expect(result.completion.values).toEqual(['Alice', 'Bob', 'Charlie']); - expect(result.completion.total).toBe(3); - }); - - /*** - * Test: Filtered Prompt Argument Completion - */ - test('should support filtered completion of prompt arguments', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.prompt( - 'test-prompt', - { - name: completable(z.string(), test => ['Alice', 'Bob', 'Charlie'].filter(value => value.startsWith(test))) - }, - async ({ name }) => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `Hello ${name}` - } - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/prompt', - name: 'test-prompt' - }, - argument: { - name: 'name', - value: 'A' - } - } - }, - CompleteResultSchema - ); - - expect(result.completion.values).toEqual(['Alice']); - expect(result.completion.total).toBe(1); - }); - - /*** - * Test: Pass Request ID to Prompt Callback - */ - test('should pass requestId to prompt callback via RequestHandlerExtra', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - let receivedRequestId: string | number | undefined; - mcpServer.prompt('request-id-test', async extra => { - receivedRequestId = extra.requestId; - return { - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `Received request ID: ${extra.requestId}` - } - } - ] - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'prompts/get', - params: { - name: 'request-id-test' - } - }, - GetPromptResultSchema - ); - - expect(receivedRequestId).toBeDefined(); - expect(typeof receivedRequestId === 'string' || typeof receivedRequestId === 'number').toBe(true); - expect(result.messages[0].content.text).toContain('Received request ID:'); - }); - - /*** - * Test: Resource Template Metadata Priority - */ - test('should prioritize individual resource metadata over template metadata', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource( - 'test', - new ResourceTemplate('test://resource/{id}', { - list: async () => ({ - resources: [ - { - name: 'Resource 1', - uri: 'test://resource/1', - description: 'Individual resource description', - mimeType: 'text/plain' - }, - { - name: 'Resource 2', - uri: 'test://resource/2' - // This resource has no description or mimeType - } - ] - }) - }), - { - description: 'Template description', - mimeType: 'application/json' - }, - async uri => ({ - contents: [ - { - uri: uri.href, - text: 'Test content' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'resources/list' - }, - ListResourcesResultSchema - ); - - expect(result.resources).toHaveLength(2); - - // Resource 1 should have its own metadata - expect(result.resources[0].name).toBe('Resource 1'); - expect(result.resources[0].description).toBe('Individual resource description'); - expect(result.resources[0].mimeType).toBe('text/plain'); - - // Resource 2 should inherit template metadata - expect(result.resources[1].name).toBe('Resource 2'); - expect(result.resources[1].description).toBe('Template description'); - expect(result.resources[1].mimeType).toBe('application/json'); - }); - - /*** - * Test: Resource Template Metadata Overrides All Fields - */ - test('should allow resource to override all template metadata fields', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.resource( - 'test', - new ResourceTemplate('test://resource/{id}', { - list: async () => ({ - resources: [ - { - name: 'Overridden Name', - uri: 'test://resource/1', - description: 'Overridden description', - mimeType: 'text/markdown' - // Add any other metadata fields if they exist - } - ] - }) - }), - { - name: 'Template Name', - description: 'Template description', - mimeType: 'application/json' - }, - async uri => ({ - contents: [ - { - uri: uri.href, - text: 'Test content' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'resources/list' - }, - ListResourcesResultSchema - ); - - expect(result.resources).toHaveLength(1); - - // All fields should be from the individual resource, not the template - expect(result.resources[0].name).toBe('Overridden Name'); - expect(result.resources[0].description).toBe('Overridden description'); - expect(result.resources[0].mimeType).toBe('text/markdown'); - }); -}); - -describe('Tool title precedence', () => { - test('should follow correct title precedence: title → annotations.title → name', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - // Tool 1: Only name - mcpServer.tool('tool_name_only', async () => ({ - content: [{ type: 'text', text: 'Response' }] - })); - - // Tool 2: Name and annotations.title - mcpServer.tool( - 'tool_with_annotations_title', - 'Tool with annotations title', - { - title: 'Annotations Title' - }, - async () => ({ - content: [{ type: 'text', text: 'Response' }] - }) - ); - - // Tool 3: Name and title (using registerTool) - mcpServer.registerTool( - 'tool_with_title', - { - title: 'Regular Title', - description: 'Tool with regular title' - }, - async () => ({ - content: [{ type: 'text', text: 'Response' }] - }) - ); - - // Tool 4: All three - title should win - mcpServer.registerTool( - 'tool_with_all_titles', - { - title: 'Regular Title Wins', - description: 'Tool with all titles', - annotations: { - title: 'Annotations Title Should Not Show' - } - }, - async () => ({ - content: [{ type: 'text', text: 'Response' }] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - await Promise.all([client.connect(clientTransport), mcpServer.connect(serverTransport)]); - - const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); - - expect(result.tools).toHaveLength(4); - - // Tool 1: Only name - should display name - const tool1 = result.tools.find(t => t.name === 'tool_name_only'); - expect(tool1).toBeDefined(); - expect(getDisplayName(tool1!)).toBe('tool_name_only'); - - // Tool 2: Name and annotations.title - should display annotations.title - const tool2 = result.tools.find(t => t.name === 'tool_with_annotations_title'); - expect(tool2).toBeDefined(); - expect(tool2!.annotations?.title).toBe('Annotations Title'); - expect(getDisplayName(tool2!)).toBe('Annotations Title'); - - // Tool 3: Name and title - should display title - const tool3 = result.tools.find(t => t.name === 'tool_with_title'); - expect(tool3).toBeDefined(); - expect(tool3!.title).toBe('Regular Title'); - expect(getDisplayName(tool3!)).toBe('Regular Title'); - - // Tool 4: All three - title should take precedence - const tool4 = result.tools.find(t => t.name === 'tool_with_all_titles'); - expect(tool4).toBeDefined(); - expect(tool4!.title).toBe('Regular Title Wins'); - expect(tool4!.annotations?.title).toBe('Annotations Title Should Not Show'); - expect(getDisplayName(tool4!)).toBe('Regular Title Wins'); - }); - - test('getDisplayName unit tests for title precedence', () => { - // Test 1: Only name - expect(getDisplayName({ name: 'tool_name' })).toBe('tool_name'); - - // Test 2: Name and title - title wins - expect( - getDisplayName({ - name: 'tool_name', - title: 'Tool Title' - }) - ).toBe('Tool Title'); - - // Test 3: Name and annotations.title - annotations.title wins - expect( - getDisplayName({ - name: 'tool_name', - annotations: { title: 'Annotations Title' } - }) - ).toBe('Annotations Title'); - - // Test 4: All three - title wins (correct precedence) - expect( - getDisplayName({ - name: 'tool_name', - title: 'Regular Title', - annotations: { title: 'Annotations Title' } - }) - ).toBe('Regular Title'); - - // Test 5: Empty title should not be used - expect( - getDisplayName({ - name: 'tool_name', - title: '', - annotations: { title: 'Annotations Title' } - }) - ).toBe('Annotations Title'); - - // Test 6: Undefined vs null handling - expect( - getDisplayName({ - name: 'tool_name', - title: undefined, - annotations: { title: 'Annotations Title' } - }) - ).toBe('Annotations Title'); - }); - - test('should support resource template completion with resolved context', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.registerResource( - 'test', - new ResourceTemplate('github://repos/{owner}/{repo}', { - list: undefined, - complete: { - repo: (value, context) => { - if (context?.arguments?.['owner'] === 'org1') { - return ['project1', 'project2', 'project3'].filter(r => r.startsWith(value)); - } else if (context?.arguments?.['owner'] === 'org2') { - return ['repo1', 'repo2', 'repo3'].filter(r => r.startsWith(value)); - } - return []; - } - } - }), - { - title: 'GitHub Repository', - description: 'Repository information' - }, - async () => ({ - contents: [ - { - uri: 'github://repos/test/test', - text: 'Test content' - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - // Test with microsoft owner - const result1 = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/resource', - uri: 'github://repos/{owner}/{repo}' - }, - argument: { - name: 'repo', - value: 'p' - }, - context: { - arguments: { - owner: 'org1' - } - } - } - }, - CompleteResultSchema - ); - - expect(result1.completion.values).toEqual(['project1', 'project2', 'project3']); - expect(result1.completion.total).toBe(3); - - // Test with facebook owner - const result2 = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/resource', - uri: 'github://repos/{owner}/{repo}' - }, - argument: { - name: 'repo', - value: 'r' - }, - context: { - arguments: { - owner: 'org2' - } - } - } - }, - CompleteResultSchema - ); - - expect(result2.completion.values).toEqual(['repo1', 'repo2', 'repo3']); - expect(result2.completion.total).toBe(3); - - // Test with no resolved context - const result3 = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/resource', - uri: 'github://repos/{owner}/{repo}' - }, - argument: { - name: 'repo', - value: 't' - } - } - }, - CompleteResultSchema - ); - - expect(result3.completion.values).toEqual([]); - expect(result3.completion.total).toBe(0); - }); - - test('should support prompt argument completion with resolved context', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.registerPrompt( - 'test-prompt', - { - title: 'Team Greeting', - description: 'Generate a greeting for team members', - argsSchema: { - department: completable(z.string(), value => { - return ['engineering', 'sales', 'marketing', 'support'].filter(d => d.startsWith(value)); - }), - name: completable(z.string(), (value, context) => { - const department = context?.arguments?.['department']; - if (department === 'engineering') { - return ['Alice', 'Bob', 'Charlie'].filter(n => n.startsWith(value)); - } else if (department === 'sales') { - return ['David', 'Eve', 'Frank'].filter(n => n.startsWith(value)); - } else if (department === 'marketing') { - return ['Grace', 'Henry', 'Iris'].filter(n => n.startsWith(value)); - } - return ['Guest'].filter(n => n.startsWith(value)); - }) - } - }, - async ({ department, name }) => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `Hello ${name}, welcome to the ${department} team!` - } - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - // Test with engineering department - const result1 = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/prompt', - name: 'test-prompt' - }, - argument: { - name: 'name', - value: 'A' - }, - context: { - arguments: { - department: 'engineering' - } - } - } - }, - CompleteResultSchema - ); - - expect(result1.completion.values).toEqual(['Alice']); - - // Test with sales department - const result2 = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/prompt', - name: 'test-prompt' - }, - argument: { - name: 'name', - value: 'D' - }, - context: { - arguments: { - department: 'sales' - } - } - } - }, - CompleteResultSchema - ); - - expect(result2.completion.values).toEqual(['David']); - - // Test with marketing department - const result3 = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/prompt', - name: 'test-prompt' - }, - argument: { - name: 'name', - value: 'G' - }, - context: { - arguments: { - department: 'marketing' - } - } - } - }, - CompleteResultSchema - ); - - expect(result3.completion.values).toEqual(['Grace']); - - // Test with no resolved context - const result4 = await client.request( - { - method: 'completion/complete', - params: { - ref: { - type: 'ref/prompt', - name: 'test-prompt' - }, - argument: { - name: 'name', - value: 'G' - } - } - }, - CompleteResultSchema - ); - - expect(result4.completion.values).toEqual(['Guest']); - }); -}); - -describe('elicitInput()', () => { - const checkAvailability = jest.fn().mockResolvedValue(false); - const findAlternatives = jest.fn().mockResolvedValue([]); - const makeBooking = jest.fn().mockResolvedValue('BOOKING-123'); - - let mcpServer: McpServer; - let client: Client; - - beforeEach(() => { - jest.clearAllMocks(); - - // Create server with restaurant booking tool - mcpServer = new McpServer({ - name: 'restaurant-booking-server', - version: '1.0.0' - }); - - // Register the restaurant booking tool from README example - mcpServer.tool( - 'book-restaurant', - { - restaurant: z.string(), - date: z.string(), - partySize: z.number() - }, - async ({ restaurant, date, partySize }) => { - // Check availability - const available = await checkAvailability(restaurant, date, partySize); - - if (!available) { - // Ask user if they want to try alternative dates - const result = await mcpServer.server.elicitInput({ - message: `No tables available at ${restaurant} on ${date}. Would you like to check alternative dates?`, - requestedSchema: { - type: 'object', - properties: { - checkAlternatives: { - type: 'boolean', - title: 'Check alternative dates', - description: 'Would you like me to check other dates?' - }, - flexibleDates: { - type: 'string', - title: 'Date flexibility', - description: 'How flexible are your dates?', - enum: ['next_day', 'same_week', 'next_week'], - enumNames: ['Next day', 'Same week', 'Next week'] - } - }, - required: ['checkAlternatives'] - } - }); - - if (result.action === 'accept' && result.content?.checkAlternatives) { - const alternatives = await findAlternatives(restaurant, date, partySize, result.content.flexibleDates as string); - return { - content: [ - { - type: 'text', - text: `Found these alternatives: ${alternatives.join(', ')}` - } - ] - }; - } - - return { - content: [ - { - type: 'text', - text: 'No booking made. Original date not available.' - } - ] - }; - } - - await makeBooking(restaurant, date, partySize); - return { - content: [ - { - type: 'text', - text: `Booked table for ${partySize} at ${restaurant} on ${date}` - } - ] - }; - } - ); - - // Create client with elicitation capability - client = new Client( - { - name: 'test-client', - version: '1.0.0' - }, - { - capabilities: { - elicitation: {} - } - } - ); - }); - - test('should successfully elicit additional information', async () => { - // Mock availability check to return false - checkAvailability.mockResolvedValue(false); - findAlternatives.mockResolvedValue(['2024-12-26', '2024-12-27', '2024-12-28']); - - // Set up client to accept alternative date checking - client.setRequestHandler(ElicitRequestSchema, async request => { - expect(request.params.message).toContain('No tables available at ABC Restaurant on 2024-12-25'); - return { - action: 'accept', - content: { - checkAlternatives: true, - flexibleDates: 'same_week' - } - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - // Call the tool - const result = await client.callTool({ - name: 'book-restaurant', - arguments: { - restaurant: 'ABC Restaurant', - date: '2024-12-25', - partySize: 2 - } - }); - - expect(checkAvailability).toHaveBeenCalledWith('ABC Restaurant', '2024-12-25', 2); - expect(findAlternatives).toHaveBeenCalledWith('ABC Restaurant', '2024-12-25', 2, 'same_week'); - expect(result.content).toEqual([ - { - type: 'text', - text: 'Found these alternatives: 2024-12-26, 2024-12-27, 2024-12-28' - } - ]); - }); - - test('should handle user declining to elicitation request', async () => { - // Mock availability check to return false - checkAvailability.mockResolvedValue(false); - - // Set up client to reject alternative date checking - client.setRequestHandler(ElicitRequestSchema, async () => { - return { - action: 'accept', - content: { - checkAlternatives: false - } - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - // Call the tool - const result = await client.callTool({ - name: 'book-restaurant', - arguments: { - restaurant: 'ABC Restaurant', - date: '2024-12-25', - partySize: 2 - } - }); - - expect(checkAvailability).toHaveBeenCalledWith('ABC Restaurant', '2024-12-25', 2); - expect(findAlternatives).not.toHaveBeenCalled(); - expect(result.content).toEqual([ - { - type: 'text', - text: 'No booking made. Original date not available.' - } - ]); - }); - - test('should handle user cancelling the elicitation', async () => { - // Mock availability check to return false - checkAvailability.mockResolvedValue(false); - - // Set up client to cancel the elicitation - client.setRequestHandler(ElicitRequestSchema, async () => { - return { - action: 'cancel' - }; - }); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - // Call the tool - const result = await client.callTool({ - name: 'book-restaurant', - arguments: { - restaurant: 'ABC Restaurant', - date: '2024-12-25', - partySize: 2 - } - }); - - expect(checkAvailability).toHaveBeenCalledWith('ABC Restaurant', '2024-12-25', 2); - expect(findAlternatives).not.toHaveBeenCalled(); - expect(result.content).toEqual([ - { - type: 'text', - text: 'No booking made. Original date not available.' - } - ]); - }); -}); diff --git a/typescript-sdk/src/server/mcp.ts b/typescript-sdk/src/server/mcp.ts deleted file mode 100644 index 765ba86..0000000 --- a/typescript-sdk/src/server/mcp.ts +++ /dev/null @@ -1,1197 +0,0 @@ -import { Server, ServerOptions } from './index.js'; -import { zodToJsonSchema } from 'zod-to-json-schema'; -import { z, ZodRawShape, ZodObject, ZodString, AnyZodObject, ZodTypeAny, ZodType, ZodTypeDef, ZodOptional } from 'zod'; -import { - Implementation, - Tool, - ListToolsResult, - CallToolResult, - McpError, - ErrorCode, - CompleteRequest, - CompleteResult, - PromptReference, - ResourceTemplateReference, - BaseMetadata, - Resource, - ListResourcesResult, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - ListToolsRequestSchema, - CallToolRequestSchema, - ListResourcesRequestSchema, - ListPromptsRequestSchema, - GetPromptRequestSchema, - CompleteRequestSchema, - ListPromptsResult, - Prompt, - PromptArgument, - GetPromptResult, - ReadResourceResult, - ServerRequest, - ServerNotification, - ToolAnnotations, - LoggingMessageNotification -} from '../types.js'; -import { Completable, CompletableDef } from './completable.js'; -import { UriTemplate, Variables } from '../shared/uriTemplate.js'; -import { RequestHandlerExtra } from '../shared/protocol.js'; -import { Transport } from '../shared/transport.js'; - -/** - * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. - * For advanced usage (like sending notifications or setting custom request handlers), use the underlying - * Server instance available via the `server` property. - */ -export class McpServer { - /** - * The underlying Server instance, useful for advanced operations like sending notifications. - */ - public readonly server: Server; - - private _registeredResources: { [uri: string]: RegisteredResource } = {}; - private _registeredResourceTemplates: { - [name: string]: RegisteredResourceTemplate; - } = {}; - private _registeredTools: { [name: string]: RegisteredTool } = {}; - private _registeredPrompts: { [name: string]: RegisteredPrompt } = {}; - - constructor(serverInfo: Implementation, options?: ServerOptions) { - this.server = new Server(serverInfo, options); - } - - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - async connect(transport: Transport): Promise { - return await this.server.connect(transport); - } - - /** - * Closes the connection. - */ - async close(): Promise { - await this.server.close(); - } - - private _toolHandlersInitialized = false; - - private setToolRequestHandlers() { - if (this._toolHandlersInitialized) { - return; - } - - this.server.assertCanSetRequestHandler(ListToolsRequestSchema.shape.method.value); - this.server.assertCanSetRequestHandler(CallToolRequestSchema.shape.method.value); - - this.server.registerCapabilities({ - tools: { - listChanged: true - } - }); - - this.server.setRequestHandler( - ListToolsRequestSchema, - (): ListToolsResult => ({ - tools: Object.entries(this._registeredTools) - .filter(([, tool]) => tool.enabled) - .map(([name, tool]): Tool => { - const toolDefinition: Tool = { - name, - title: tool.title, - description: tool.description, - inputSchema: tool.inputSchema - ? (zodToJsonSchema(tool.inputSchema, { - strictUnions: true, - pipeStrategy: 'input' - }) as Tool['inputSchema']) - : EMPTY_OBJECT_JSON_SCHEMA, - annotations: tool.annotations, - _meta: tool._meta - }; - - if (tool.outputSchema) { - toolDefinition.outputSchema = zodToJsonSchema(tool.outputSchema, { - strictUnions: true, - pipeStrategy: 'output' - }) as Tool['outputSchema']; - } - - return toolDefinition; - }) - }) - ); - - this.server.setRequestHandler(CallToolRequestSchema, async (request, extra): Promise => { - const tool = this._registeredTools[request.params.name]; - if (!tool) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - } - - if (!tool.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - } - - let result: CallToolResult; - - if (tool.inputSchema) { - const parseResult = await tool.inputSchema.safeParseAsync(request.params.arguments); - if (!parseResult.success) { - throw new McpError( - ErrorCode.InvalidParams, - `Invalid arguments for tool ${request.params.name}: ${parseResult.error.message}` - ); - } - - const args = parseResult.data; - const cb = tool.callback as ToolCallback; - try { - result = await Promise.resolve(cb(args, extra)); - } catch (error) { - result = { - content: [ - { - type: 'text', - text: error instanceof Error ? error.message : String(error) - } - ], - isError: true - }; - } - } else { - const cb = tool.callback as ToolCallback; - try { - result = await Promise.resolve(cb(extra)); - } catch (error) { - result = { - content: [ - { - type: 'text', - text: error instanceof Error ? error.message : String(error) - } - ], - isError: true - }; - } - } - - if (tool.outputSchema && !result.isError) { - if (!result.structuredContent) { - throw new McpError( - ErrorCode.InvalidParams, - `Tool ${request.params.name} has an output schema but no structured content was provided` - ); - } - - // if the tool has an output schema, validate structured content - const parseResult = await tool.outputSchema.safeParseAsync(result.structuredContent); - if (!parseResult.success) { - throw new McpError( - ErrorCode.InvalidParams, - `Invalid structured content for tool ${request.params.name}: ${parseResult.error.message}` - ); - } - } - - return result; - }); - - this._toolHandlersInitialized = true; - } - - private _completionHandlerInitialized = false; - - private setCompletionRequestHandler() { - if (this._completionHandlerInitialized) { - return; - } - - this.server.assertCanSetRequestHandler(CompleteRequestSchema.shape.method.value); - - this.server.registerCapabilities({ - completions: {} - }); - - this.server.setRequestHandler(CompleteRequestSchema, async (request): Promise => { - switch (request.params.ref.type) { - case 'ref/prompt': - return this.handlePromptCompletion(request, request.params.ref); - - case 'ref/resource': - return this.handleResourceCompletion(request, request.params.ref); - - default: - throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - - this._completionHandlerInitialized = true; - } - - private async handlePromptCompletion(request: CompleteRequest, ref: PromptReference): Promise { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - } - - if (!prompt.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - } - - if (!prompt.argsSchema) { - return EMPTY_COMPLETION_RESULT; - } - - const field = prompt.argsSchema.shape[request.params.argument.name]; - if (!(field instanceof Completable)) { - return EMPTY_COMPLETION_RESULT; - } - - const def: CompletableDef = field._def; - const suggestions = await def.complete(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); - } - - private async handleResourceCompletion(request: CompleteRequest, ref: ResourceTemplateReference): Promise { - const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri); - - if (!template) { - if (this._registeredResources[ref.uri]) { - // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be). - return EMPTY_COMPLETION_RESULT; - } - - throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) { - return EMPTY_COMPLETION_RESULT; - } - - const suggestions = await completer(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); - } - - private _resourceHandlersInitialized = false; - - private setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) { - return; - } - - this.server.assertCanSetRequestHandler(ListResourcesRequestSchema.shape.method.value); - this.server.assertCanSetRequestHandler(ListResourceTemplatesRequestSchema.shape.method.value); - this.server.assertCanSetRequestHandler(ReadResourceRequestSchema.shape.method.value); - - this.server.registerCapabilities({ - resources: { - listChanged: true - } - }); - - this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { - const resources = Object.entries(this._registeredResources) - .filter(([_, resource]) => resource.enabled) - .map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - - const templateResources: Resource[] = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) { - continue; - } - - const result = await template.resourceTemplate.listCallback(extra); - for (const resource of result.resources) { - templateResources.push({ - ...template.metadata, - // the defined resource metadata should override the template metadata if present - ...resource - }); - } - } - - return { resources: [...resources, ...templateResources] }; - }); - - this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => { - const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })); - - return { resourceTemplates }; - }); - - this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { - const uri = new URL(request.params.uri); - - // First check for exact resource match - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`); - } - return resource.readCallback(uri, extra); - } - - // Then check templates - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) { - return template.readCallback(uri, variables, extra); - } - } - - throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`); - }); - - this.setCompletionRequestHandler(); - - this._resourceHandlersInitialized = true; - } - - private _promptHandlersInitialized = false; - - private setPromptRequestHandlers() { - if (this._promptHandlersInitialized) { - return; - } - - this.server.assertCanSetRequestHandler(ListPromptsRequestSchema.shape.method.value); - this.server.assertCanSetRequestHandler(GetPromptRequestSchema.shape.method.value); - - this.server.registerCapabilities({ - prompts: { - listChanged: true - } - }); - - this.server.setRequestHandler( - ListPromptsRequestSchema, - (): ListPromptsResult => ({ - prompts: Object.entries(this._registeredPrompts) - .filter(([, prompt]) => prompt.enabled) - .map(([name, prompt]): Prompt => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined - }; - }) - }) - ); - - this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra): Promise => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - } - - if (!prompt.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - } - - if (prompt.argsSchema) { - const parseResult = await prompt.argsSchema.safeParseAsync(request.params.arguments); - if (!parseResult.success) { - throw new McpError( - ErrorCode.InvalidParams, - `Invalid arguments for prompt ${request.params.name}: ${parseResult.error.message}` - ); - } - - const args = parseResult.data; - const cb = prompt.callback as PromptCallback; - return await Promise.resolve(cb(args, extra)); - } else { - const cb = prompt.callback as PromptCallback; - return await Promise.resolve(cb(extra)); - } - }); - - this.setCompletionRequestHandler(); - - this._promptHandlersInitialized = true; - } - - /** - * Registers a resource `name` at a fixed URI, which will use the given callback to respond to read requests. - */ - resource(name: string, uri: string, readCallback: ReadResourceCallback): RegisteredResource; - - /** - * Registers a resource `name` at a fixed URI with metadata, which will use the given callback to respond to read requests. - */ - resource(name: string, uri: string, metadata: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; - - /** - * Registers a resource `name` with a template pattern, which will use the given callback to respond to read requests. - */ - resource(name: string, template: ResourceTemplate, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; - - /** - * Registers a resource `name` with a template pattern and metadata, which will use the given callback to respond to read requests. - */ - resource( - name: string, - template: ResourceTemplate, - metadata: ResourceMetadata, - readCallback: ReadResourceTemplateCallback - ): RegisteredResourceTemplate; - - resource(name: string, uriOrTemplate: string | ResourceTemplate, ...rest: unknown[]): RegisteredResource | RegisteredResourceTemplate { - let metadata: ResourceMetadata | undefined; - if (typeof rest[0] === 'object') { - metadata = rest.shift() as ResourceMetadata; - } - - const readCallback = rest[0] as ReadResourceCallback | ReadResourceTemplateCallback; - - if (typeof uriOrTemplate === 'string') { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - - const registeredResource = this._createRegisteredResource( - name, - undefined, - uriOrTemplate, - metadata, - readCallback as ReadResourceCallback - ); - - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name]) { - throw new Error(`Resource template ${name} is already registered`); - } - - const registeredResourceTemplate = this._createRegisteredResourceTemplate( - name, - undefined, - uriOrTemplate, - metadata, - readCallback as ReadResourceTemplateCallback - ); - - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - - /** - * Registers a resource with a config object and callback. - * For static resources, use a URI string. For dynamic resources, use a ResourceTemplate. - */ - registerResource(name: string, uriOrTemplate: string, config: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; - registerResource( - name: string, - uriOrTemplate: ResourceTemplate, - config: ResourceMetadata, - readCallback: ReadResourceTemplateCallback - ): RegisteredResourceTemplate; - registerResource( - name: string, - uriOrTemplate: string | ResourceTemplate, - config: ResourceMetadata, - readCallback: ReadResourceCallback | ReadResourceTemplateCallback - ): RegisteredResource | RegisteredResourceTemplate { - if (typeof uriOrTemplate === 'string') { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - - const registeredResource = this._createRegisteredResource( - name, - (config as BaseMetadata).title, - uriOrTemplate, - config, - readCallback as ReadResourceCallback - ); - - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name]) { - throw new Error(`Resource template ${name} is already registered`); - } - - const registeredResourceTemplate = this._createRegisteredResourceTemplate( - name, - (config as BaseMetadata).title, - uriOrTemplate, - config, - readCallback as ReadResourceTemplateCallback - ); - - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - - private _createRegisteredResource( - name: string, - title: string | undefined, - uri: string, - metadata: ResourceMetadata | undefined, - readCallback: ReadResourceCallback - ): RegisteredResource { - const registeredResource: RegisteredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: updates => { - if (typeof updates.uri !== 'undefined' && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) this._registeredResources[updates.uri] = registeredResource; - } - if (typeof updates.name !== 'undefined') registeredResource.name = updates.name; - if (typeof updates.title !== 'undefined') registeredResource.title = updates.title; - if (typeof updates.metadata !== 'undefined') registeredResource.metadata = updates.metadata; - if (typeof updates.callback !== 'undefined') registeredResource.readCallback = updates.callback; - if (typeof updates.enabled !== 'undefined') registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - - private _createRegisteredResourceTemplate( - name: string, - title: string | undefined, - template: ResourceTemplate, - metadata: ResourceMetadata | undefined, - readCallback: ReadResourceTemplateCallback - ): RegisteredResourceTemplate { - const registeredResourceTemplate: RegisteredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (typeof updates.title !== 'undefined') registeredResourceTemplate.title = updates.title; - if (typeof updates.template !== 'undefined') registeredResourceTemplate.resourceTemplate = updates.template; - if (typeof updates.metadata !== 'undefined') registeredResourceTemplate.metadata = updates.metadata; - if (typeof updates.callback !== 'undefined') registeredResourceTemplate.readCallback = updates.callback; - if (typeof updates.enabled !== 'undefined') registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - return registeredResourceTemplate; - } - - private _createRegisteredPrompt( - name: string, - title: string | undefined, - description: string | undefined, - argsSchema: PromptArgsRawShape | undefined, - callback: PromptCallback - ): RegisteredPrompt { - const registeredPrompt: RegisteredPrompt = { - title, - description, - argsSchema: argsSchema === undefined ? undefined : z.object(argsSchema), - callback, - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; - } - if (typeof updates.title !== 'undefined') registeredPrompt.title = updates.title; - if (typeof updates.description !== 'undefined') registeredPrompt.description = updates.description; - if (typeof updates.argsSchema !== 'undefined') registeredPrompt.argsSchema = z.object(updates.argsSchema); - if (typeof updates.callback !== 'undefined') registeredPrompt.callback = updates.callback; - if (typeof updates.enabled !== 'undefined') registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - return registeredPrompt; - } - - private _createRegisteredTool( - name: string, - title: string | undefined, - description: string | undefined, - inputSchema: ZodRawShape | undefined, - outputSchema: ZodRawShape | undefined, - annotations: ToolAnnotations | undefined, - _meta: Record | undefined, - callback: ToolCallback - ): RegisteredTool { - const registeredTool: RegisteredTool = { - title, - description, - inputSchema: inputSchema === undefined ? undefined : z.object(inputSchema), - outputSchema: outputSchema === undefined ? undefined : z.object(outputSchema), - annotations, - _meta, - callback, - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - delete this._registeredTools[name]; - if (updates.name) this._registeredTools[updates.name] = registeredTool; - } - if (typeof updates.title !== 'undefined') registeredTool.title = updates.title; - if (typeof updates.description !== 'undefined') registeredTool.description = updates.description; - if (typeof updates.paramsSchema !== 'undefined') registeredTool.inputSchema = z.object(updates.paramsSchema); - if (typeof updates.callback !== 'undefined') registeredTool.callback = updates.callback; - if (typeof updates.annotations !== 'undefined') registeredTool.annotations = updates.annotations; - if (typeof updates._meta !== 'undefined') registeredTool._meta = updates._meta; - if (typeof updates.enabled !== 'undefined') registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - - this.setToolRequestHandlers(); - this.sendToolListChanged(); - - return registeredTool; - } - - /** - * Registers a zero-argument tool `name`, which will run the given function when the client calls it. - */ - tool(name: string, cb: ToolCallback): RegisteredTool; - - /** - * Registers a zero-argument tool `name` (with a description) which will run the given function when the client calls it. - */ - tool(name: string, description: string, cb: ToolCallback): RegisteredTool; - - /** - * Registers a tool taking either a parameter schema for validation or annotations for additional metadata. - * This unified overload handles both `tool(name, paramsSchema, cb)` and `tool(name, annotations, cb)` cases. - * - * Note: We use a union type for the second parameter because TypeScript cannot reliably disambiguate - * between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types. - */ - tool(name: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; - - /** - * Registers a tool `name` (with a description) taking either parameter schema or annotations. - * This unified overload handles both `tool(name, description, paramsSchema, cb)` and - * `tool(name, description, annotations, cb)` cases. - * - * Note: We use a union type for the third parameter because TypeScript cannot reliably disambiguate - * between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types. - */ - tool( - name: string, - description: string, - paramsSchemaOrAnnotations: Args | ToolAnnotations, - cb: ToolCallback - ): RegisteredTool; - - /** - * Registers a tool with both parameter schema and annotations. - */ - tool(name: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; - - /** - * Registers a tool with description, parameter schema, and annotations. - */ - tool( - name: string, - description: string, - paramsSchema: Args, - annotations: ToolAnnotations, - cb: ToolCallback - ): RegisteredTool; - - /** - * tool() implementation. Parses arguments passed to overrides defined above. - */ - tool(name: string, ...rest: unknown[]): RegisteredTool { - if (this._registeredTools[name]) { - throw new Error(`Tool ${name} is already registered`); - } - - let description: string | undefined; - let inputSchema: ZodRawShape | undefined; - let outputSchema: ZodRawShape | undefined; - let annotations: ToolAnnotations | undefined; - - // Tool properties are passed as separate arguments, with omissions allowed. - // Support for this style is frozen as of protocol version 2025-03-26. Future additions - // to tool definition should *NOT* be added. - - if (typeof rest[0] === 'string') { - description = rest.shift() as string; - } - - // Handle the different overload combinations - if (rest.length > 1) { - // We have at least one more arg before the callback - const firstArg = rest[0]; - - if (isZodRawShape(firstArg)) { - // We have a params schema as the first arg - inputSchema = rest.shift() as ZodRawShape; - - // Check if the next arg is potentially annotations - if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShape(rest[0])) { - // Case: tool(name, paramsSchema, annotations, cb) - // Or: tool(name, description, paramsSchema, annotations, cb) - annotations = rest.shift() as ToolAnnotations; - } - } else if (typeof firstArg === 'object' && firstArg !== null) { - // Not a ZodRawShape, so must be annotations in this position - // Case: tool(name, annotations, cb) - // Or: tool(name, description, annotations, cb) - annotations = rest.shift() as ToolAnnotations; - } - } - const callback = rest[0] as ToolCallback; - - return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, undefined, callback); - } - - /** - * Registers a tool with a config object and callback. - */ - registerTool( - name: string, - config: { - title?: string; - description?: string; - inputSchema?: InputArgs; - outputSchema?: OutputArgs; - annotations?: ToolAnnotations; - _meta?: Record; - }, - cb: ToolCallback - ): RegisteredTool { - if (this._registeredTools[name]) { - throw new Error(`Tool ${name} is already registered`); - } - - const { title, description, inputSchema, outputSchema, annotations, _meta } = config; - - return this._createRegisteredTool( - name, - title, - description, - inputSchema, - outputSchema, - annotations, - _meta, - cb as ToolCallback - ); - } - - /** - * Registers a zero-argument prompt `name`, which will run the given function when the client calls it. - */ - prompt(name: string, cb: PromptCallback): RegisteredPrompt; - - /** - * Registers a zero-argument prompt `name` (with a description) which will run the given function when the client calls it. - */ - prompt(name: string, description: string, cb: PromptCallback): RegisteredPrompt; - - /** - * Registers a prompt `name` accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. - */ - prompt(name: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; - - /** - * Registers a prompt `name` (with a description) accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. - */ - prompt( - name: string, - description: string, - argsSchema: Args, - cb: PromptCallback - ): RegisteredPrompt; - - prompt(name: string, ...rest: unknown[]): RegisteredPrompt { - if (this._registeredPrompts[name]) { - throw new Error(`Prompt ${name} is already registered`); - } - - let description: string | undefined; - if (typeof rest[0] === 'string') { - description = rest.shift() as string; - } - - let argsSchema: PromptArgsRawShape | undefined; - if (rest.length > 1) { - argsSchema = rest.shift() as PromptArgsRawShape; - } - - const cb = rest[0] as PromptCallback; - const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb); - - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - - return registeredPrompt; - } - - /** - * Registers a prompt with a config object and callback. - */ - registerPrompt( - name: string, - config: { - title?: string; - description?: string; - argsSchema?: Args; - }, - cb: PromptCallback - ): RegisteredPrompt { - if (this._registeredPrompts[name]) { - throw new Error(`Prompt ${name} is already registered`); - } - - const { title, description, argsSchema } = config; - - const registeredPrompt = this._createRegisteredPrompt( - name, - title, - description, - argsSchema, - cb as PromptCallback - ); - - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - - return registeredPrompt; - } - - /** - * Checks if the server is connected to a transport. - * @returns True if the server is connected - */ - isConnected() { - return this.server.transport !== undefined; - } - - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - async sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string) { - return this.server.sendLoggingMessage(params, sessionId); - } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) { - this.server.sendResourceListChanged(); - } - } - - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) { - this.server.sendToolListChanged(); - } - } - - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) { - this.server.sendPromptListChanged(); - } - } -} - -/** - * A callback to complete one variable within a resource template's URI template. - */ -export type CompleteResourceTemplateCallback = ( - value: string, - context?: { - arguments?: Record; - } -) => string[] | Promise; - -/** - * A resource template combines a URI pattern with optional functionality to enumerate - * all resources matching that pattern. - */ -export class ResourceTemplate { - private _uriTemplate: UriTemplate; - - constructor( - uriTemplate: string | UriTemplate, - private _callbacks: { - /** - * A callback to list all resources matching this template. This is required to specified, even if `undefined`, to avoid accidentally forgetting resource listing. - */ - list: ListResourcesCallback | undefined; - - /** - * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values. - */ - complete?: { - [variable: string]: CompleteResourceTemplateCallback; - }; - } - ) { - this._uriTemplate = typeof uriTemplate === 'string' ? new UriTemplate(uriTemplate) : uriTemplate; - } - - /** - * Gets the URI template pattern. - */ - get uriTemplate(): UriTemplate { - return this._uriTemplate; - } - - /** - * Gets the list callback, if one was provided. - */ - get listCallback(): ListResourcesCallback | undefined { - return this._callbacks.list; - } - - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable: string): CompleteResourceTemplateCallback | undefined { - return this._callbacks.complete?.[variable]; - } -} - -/** - * Callback for a tool handler registered with Server.tool(). - * - * Parameters will include tool arguments, if applicable, as well as other request handler context. - * - * The callback should return: - * - `structuredContent` if the tool has an outputSchema defined - * - `content` if the tool does not have an outputSchema - * - Both fields are optional but typically one should be provided - */ -export type ToolCallback = Args extends ZodRawShape - ? ( - args: z.objectOutputType, - extra: RequestHandlerExtra - ) => CallToolResult | Promise - : (extra: RequestHandlerExtra) => CallToolResult | Promise; - -export type RegisteredTool = { - title?: string; - description?: string; - inputSchema?: AnyZodObject; - outputSchema?: AnyZodObject; - annotations?: ToolAnnotations; - _meta?: Record; - callback: ToolCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string | null; - title?: string; - description?: string; - paramsSchema?: InputArgs; - outputSchema?: OutputArgs; - annotations?: ToolAnnotations; - _meta?: Record; - callback?: ToolCallback; - enabled?: boolean; - }): void; - remove(): void; -}; - -const EMPTY_OBJECT_JSON_SCHEMA = { - type: 'object' as const, - properties: {} -}; - -// Helper to check if an object is a Zod schema (ZodRawShape) -function isZodRawShape(obj: unknown): obj is ZodRawShape { - if (typeof obj !== 'object' || obj === null) return false; - - const isEmptyObject = Object.keys(obj).length === 0; - - // Check if object is empty or at least one property is a ZodType instance - // Note: use heuristic check to avoid instanceof failure across different Zod versions - return isEmptyObject || Object.values(obj as object).some(isZodTypeLike); -} - -function isZodTypeLike(value: unknown): value is ZodType { - return ( - value !== null && - typeof value === 'object' && - 'parse' in value && - typeof value.parse === 'function' && - 'safeParse' in value && - typeof value.safeParse === 'function' - ); -} - -/** - * Additional, optional information for annotating a resource. - */ -export type ResourceMetadata = Omit; - -/** - * Callback to list all resources matching a given template. - */ -export type ListResourcesCallback = ( - extra: RequestHandlerExtra -) => ListResourcesResult | Promise; - -/** - * Callback to read a resource at a given URI. - */ -export type ReadResourceCallback = ( - uri: URL, - extra: RequestHandlerExtra -) => ReadResourceResult | Promise; - -export type RegisteredResource = { - name: string; - title?: string; - metadata?: ResourceMetadata; - readCallback: ReadResourceCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string; - title?: string; - uri?: string | null; - metadata?: ResourceMetadata; - callback?: ReadResourceCallback; - enabled?: boolean; - }): void; - remove(): void; -}; - -/** - * Callback to read a resource at a given URI, following a filled-in URI template. - */ -export type ReadResourceTemplateCallback = ( - uri: URL, - variables: Variables, - extra: RequestHandlerExtra -) => ReadResourceResult | Promise; - -export type RegisteredResourceTemplate = { - resourceTemplate: ResourceTemplate; - title?: string; - metadata?: ResourceMetadata; - readCallback: ReadResourceTemplateCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string | null; - title?: string; - template?: ResourceTemplate; - metadata?: ResourceMetadata; - callback?: ReadResourceTemplateCallback; - enabled?: boolean; - }): void; - remove(): void; -}; - -type PromptArgsRawShape = { - [k: string]: ZodType | ZodOptional>; -}; - -export type PromptCallback = Args extends PromptArgsRawShape - ? ( - args: z.objectOutputType, - extra: RequestHandlerExtra - ) => GetPromptResult | Promise - : (extra: RequestHandlerExtra) => GetPromptResult | Promise; - -export type RegisteredPrompt = { - title?: string; - description?: string; - argsSchema?: ZodObject; - callback: PromptCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string | null; - title?: string; - description?: string; - argsSchema?: Args; - callback?: PromptCallback; - enabled?: boolean; - }): void; - remove(): void; -}; - -function promptArgumentsFromSchema(schema: ZodObject): PromptArgument[] { - return Object.entries(schema.shape).map( - ([name, field]): PromptArgument => ({ - name, - description: field.description, - required: !field.isOptional() - }) - ); -} - -function createCompletionResult(suggestions: string[]): CompleteResult { - return { - completion: { - values: suggestions.slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } - }; -} - -const EMPTY_COMPLETION_RESULT: CompleteResult = { - completion: { - values: [], - hasMore: false - } -}; diff --git a/typescript-sdk/src/server/sse.test.ts b/typescript-sdk/src/server/sse.test.ts deleted file mode 100644 index 372cb68..0000000 --- a/typescript-sdk/src/server/sse.test.ts +++ /dev/null @@ -1,710 +0,0 @@ -import http from 'http'; -import { jest } from '@jest/globals'; -import { SSEServerTransport } from './sse.js'; -import { McpServer } from './mcp.js'; -import { createServer, type Server } from 'node:http'; -import { AddressInfo } from 'node:net'; -import { z } from 'zod'; -import { CallToolResult, JSONRPCMessage } from 'src/types.js'; - -const createMockResponse = () => { - const res = { - writeHead: jest.fn().mockReturnThis(), - write: jest.fn().mockReturnThis(), - on: jest.fn().mockReturnThis(), - end: jest.fn().mockReturnThis() - }; - - return res as unknown as jest.Mocked; -}; - -const createMockRequest = ({ headers = {}, body }: { headers?: Record; body?: string } = {}) => { - const mockReq = { - headers, - body: body ? body : undefined, - auth: { - token: 'test-token' - }, - on: jest.fn().mockImplementation((event, listener) => { - const mockListener = listener as unknown as (...args: unknown[]) => void; - if (event === 'data') { - mockListener(Buffer.from(body || '') as unknown as Error); - } - if (event === 'error') { - mockListener(new Error('test')); - } - if (event === 'end') { - mockListener(); - } - if (event === 'close') { - setTimeout(listener, 100); - } - return mockReq; - }), - listeners: jest.fn(), - removeListener: jest.fn() - } as unknown as http.IncomingMessage; - - return mockReq; -}; - -/** - * Helper to create and start test HTTP server with MCP setup - */ -async function createTestServerWithSse(args: { mockRes: http.ServerResponse }): Promise<{ - server: Server; - transport: SSEServerTransport; - mcpServer: McpServer; - baseUrl: URL; - sessionId: string; - serverPort: number; -}> { - const mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: { logging: {} } }); - - mcpServer.tool( - 'greet', - 'A simple greeting tool', - { name: z.string().describe('Name to greet') }, - async ({ name }): Promise => { - return { content: [{ type: 'text', text: `Hello, ${name}!` }] }; - } - ); - - const endpoint = '/messages'; - - const transport = new SSEServerTransport(endpoint, args.mockRes); - const sessionId = transport.sessionId; - - await mcpServer.connect(transport); - - const server = createServer(async (req, res) => { - try { - await transport.handlePostMessage(req, res); - } catch (error) { - console.error('Error handling request:', error); - if (!res.headersSent) res.writeHead(500).end(); - } - }); - - const baseUrl = await new Promise(resolve => { - server.listen(0, '127.0.0.1', () => { - const addr = server.address() as AddressInfo; - resolve(new URL(`http://127.0.0.1:${addr.port}`)); - }); - }); - - const port = (server.address() as AddressInfo).port; - - return { server, transport, mcpServer, baseUrl, sessionId, serverPort: port }; -} - -async function readAllSSEEvents(response: Response): Promise { - const reader = response.body?.getReader(); - if (!reader) throw new Error('No readable stream'); - - const events: string[] = []; - const decoder = new TextDecoder(); - - try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - - if (value) { - events.push(decoder.decode(value)); - } - } - } finally { - reader.releaseLock(); - } - - return events; -} - -/** - * Helper to send JSON-RPC request - */ -async function sendSsePostRequest( - baseUrl: URL, - message: JSONRPCMessage | JSONRPCMessage[], - sessionId?: string, - extraHeaders?: Record -): Promise { - const headers: Record = { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - ...extraHeaders - }; - - if (sessionId) { - baseUrl.searchParams.set('sessionId', sessionId); - } - - return fetch(baseUrl, { - method: 'POST', - headers, - body: JSON.stringify(message) - }); -} - -describe('SSEServerTransport', () => { - async function initializeServer(baseUrl: URL): Promise { - const response = await sendSsePostRequest(baseUrl, { - jsonrpc: '2.0', - method: 'initialize', - params: { - clientInfo: { name: 'test-client', version: '1.0' }, - protocolVersion: '2025-03-26', - capabilities: {} - }, - - id: 'init-1' - } as JSONRPCMessage); - - expect(response.status).toBe(202); - - const text = await readAllSSEEvents(response); - - expect(text).toHaveLength(1); - expect(text[0]).toBe('Accepted'); - } - - describe('start method', () => { - it('should correctly append sessionId to a simple relative endpoint', async () => { - const mockRes = createMockResponse(); - const endpoint = '/messages'; - const transport = new SSEServerTransport(endpoint, mockRes); - const expectedSessionId = transport.sessionId; - - await transport.start(); - - expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object)); - expect(mockRes.write).toHaveBeenCalledTimes(1); - expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /messages?sessionId=${expectedSessionId}\n\n`); - }); - - it('should correctly append sessionId to an endpoint with existing query parameters', async () => { - const mockRes = createMockResponse(); - const endpoint = '/messages?foo=bar&baz=qux'; - const transport = new SSEServerTransport(endpoint, mockRes); - const expectedSessionId = transport.sessionId; - - await transport.start(); - - expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object)); - expect(mockRes.write).toHaveBeenCalledTimes(1); - expect(mockRes.write).toHaveBeenCalledWith( - `event: endpoint\ndata: /messages?foo=bar&baz=qux&sessionId=${expectedSessionId}\n\n` - ); - }); - - it('should correctly append sessionId to an endpoint with a hash fragment', async () => { - const mockRes = createMockResponse(); - const endpoint = '/messages#section1'; - const transport = new SSEServerTransport(endpoint, mockRes); - const expectedSessionId = transport.sessionId; - - await transport.start(); - - expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object)); - expect(mockRes.write).toHaveBeenCalledTimes(1); - expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /messages?sessionId=${expectedSessionId}#section1\n\n`); - }); - - it('should correctly append sessionId to an endpoint with query parameters and a hash fragment', async () => { - const mockRes = createMockResponse(); - const endpoint = '/messages?key=value#section2'; - const transport = new SSEServerTransport(endpoint, mockRes); - const expectedSessionId = transport.sessionId; - - await transport.start(); - - expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object)); - expect(mockRes.write).toHaveBeenCalledTimes(1); - expect(mockRes.write).toHaveBeenCalledWith( - `event: endpoint\ndata: /messages?key=value&sessionId=${expectedSessionId}#section2\n\n` - ); - }); - - it('should correctly handle the root path endpoint "/"', async () => { - const mockRes = createMockResponse(); - const endpoint = '/'; - const transport = new SSEServerTransport(endpoint, mockRes); - const expectedSessionId = transport.sessionId; - - await transport.start(); - - expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object)); - expect(mockRes.write).toHaveBeenCalledTimes(1); - expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /?sessionId=${expectedSessionId}\n\n`); - }); - - it('should correctly handle an empty string endpoint ""', async () => { - const mockRes = createMockResponse(); - const endpoint = ''; - const transport = new SSEServerTransport(endpoint, mockRes); - const expectedSessionId = transport.sessionId; - - await transport.start(); - - expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object)); - expect(mockRes.write).toHaveBeenCalledTimes(1); - expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /?sessionId=${expectedSessionId}\n\n`); - }); - - /** - * Test: Tool With Request Info - */ - it('should pass request info to tool callback', async () => { - const mockRes = createMockResponse(); - const { mcpServer, baseUrl, sessionId, serverPort } = await createTestServerWithSse({ mockRes }); - await initializeServer(baseUrl); - - mcpServer.tool( - 'test-request-info', - 'A simple test tool with request info', - { name: z.string().describe('Name to greet') }, - async ({ name }, { requestInfo }): Promise => { - return { - content: [ - { type: 'text', text: `Hello, ${name}!` }, - { type: 'text', text: `${JSON.stringify(requestInfo)}` } - ] - }; - } - ); - - const toolCallMessage: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'tools/call', - params: { - name: 'test-request-info', - arguments: { - name: 'Test User' - } - }, - id: 'call-1' - }; - - const response = await sendSsePostRequest(baseUrl, toolCallMessage, sessionId); - - expect(response.status).toBe(202); - - expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /messages?sessionId=${sessionId}\n\n`); - - const expectedMessage = { - result: { - content: [ - { - type: 'text', - text: 'Hello, Test User!' - }, - { - type: 'text', - text: JSON.stringify({ - headers: { - host: `127.0.0.1:${serverPort}`, - connection: 'keep-alive', - 'content-type': 'application/json', - accept: 'application/json, text/event-stream', - 'accept-language': '*', - 'sec-fetch-mode': 'cors', - 'user-agent': 'node', - 'accept-encoding': 'gzip, deflate', - 'content-length': '124' - } - }) - } - ] - }, - jsonrpc: '2.0', - id: 'call-1' - }; - expect(mockRes.write).toHaveBeenCalledWith(`event: message\ndata: ${JSON.stringify(expectedMessage)}\n\n`); - }); - }); - - describe('handlePostMessage method', () => { - it('should return 500 if server has not started', async () => { - const mockReq = createMockRequest(); - const mockRes = createMockResponse(); - const endpoint = '/messages'; - const transport = new SSEServerTransport(endpoint, mockRes); - - const error = 'SSE connection not established'; - await expect(transport.handlePostMessage(mockReq, mockRes)).rejects.toThrow(error); - expect(mockRes.writeHead).toHaveBeenCalledWith(500); - expect(mockRes.end).toHaveBeenCalledWith(error); - }); - - it('should return 400 if content-type is not application/json', async () => { - const mockReq = createMockRequest({ headers: { 'content-type': 'text/plain' } }); - const mockRes = createMockResponse(); - const endpoint = '/messages'; - const transport = new SSEServerTransport(endpoint, mockRes); - await transport.start(); - - transport.onerror = jest.fn(); - const error = 'Unsupported content-type: text/plain'; - await expect(transport.handlePostMessage(mockReq, mockRes)).resolves.toBe(undefined); - expect(mockRes.writeHead).toHaveBeenCalledWith(400); - expect(mockRes.end).toHaveBeenCalledWith(expect.stringContaining(error)); - expect(transport.onerror).toHaveBeenCalledWith(new Error(error)); - }); - - it('should return 400 if message has not a valid schema', async () => { - const invalidMessage = JSON.stringify({ - // missing jsonrpc field - method: 'call', - params: [1, 2, 3], - id: 1 - }); - const mockReq = createMockRequest({ - headers: { 'content-type': 'application/json' }, - body: invalidMessage - }); - const mockRes = createMockResponse(); - const endpoint = '/messages'; - const transport = new SSEServerTransport(endpoint, mockRes); - await transport.start(); - - transport.onmessage = jest.fn(); - await transport.handlePostMessage(mockReq, mockRes); - expect(mockRes.writeHead).toHaveBeenCalledWith(400); - expect(transport.onmessage).not.toHaveBeenCalled(); - expect(mockRes.end).toHaveBeenCalledWith(`Invalid message: ${invalidMessage}`); - }); - - it('should return 202 if message has a valid schema', async () => { - const validMessage = JSON.stringify({ - jsonrpc: '2.0', - method: 'call', - params: { - a: 1, - b: 2, - c: 3 - }, - id: 1 - }); - const mockReq = createMockRequest({ - headers: { 'content-type': 'application/json' }, - body: validMessage - }); - const mockRes = createMockResponse(); - const endpoint = '/messages'; - const transport = new SSEServerTransport(endpoint, mockRes); - await transport.start(); - - transport.onmessage = jest.fn(); - await transport.handlePostMessage(mockReq, mockRes); - expect(mockRes.writeHead).toHaveBeenCalledWith(202); - expect(mockRes.end).toHaveBeenCalledWith('Accepted'); - expect(transport.onmessage).toHaveBeenCalledWith( - { - jsonrpc: '2.0', - method: 'call', - params: { - a: 1, - b: 2, - c: 3 - }, - id: 1 - }, - { - authInfo: { - token: 'test-token' - }, - requestInfo: { - headers: { - 'content-type': 'application/json' - } - } - } - ); - }); - }); - - describe('close method', () => { - it('should call onclose', async () => { - const mockRes = createMockResponse(); - const endpoint = '/messages'; - const transport = new SSEServerTransport(endpoint, mockRes); - await transport.start(); - transport.onclose = jest.fn(); - await transport.close(); - expect(transport.onclose).toHaveBeenCalled(); - }); - }); - - describe('send method', () => { - it('should call onsend', async () => { - const mockRes = createMockResponse(); - const endpoint = '/messages'; - const transport = new SSEServerTransport(endpoint, mockRes); - await transport.start(); - expect(mockRes.write).toHaveBeenCalledTimes(1); - expect(mockRes.write).toHaveBeenCalledWith(expect.stringContaining('event: endpoint')); - expect(mockRes.write).toHaveBeenCalledWith(expect.stringContaining(`data: /messages?sessionId=${transport.sessionId}`)); - }); - }); - - describe('DNS rebinding protection', () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - - describe('Host header validation', () => { - it('should accept requests with allowed host headers', async () => { - const mockRes = createMockResponse(); - const transport = new SSEServerTransport('/messages', mockRes, { - allowedHosts: ['localhost:3000', 'example.com'], - enableDnsRebindingProtection: true - }); - await transport.start(); - - const mockReq = createMockRequest({ - headers: { - host: 'localhost:3000', - 'content-type': 'application/json' - } - }); - const mockHandleRes = createMockResponse(); - - await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes.writeHead).toHaveBeenCalledWith(202); - expect(mockHandleRes.end).toHaveBeenCalledWith('Accepted'); - }); - - it('should reject requests with disallowed host headers', async () => { - const mockRes = createMockResponse(); - const transport = new SSEServerTransport('/messages', mockRes, { - allowedHosts: ['localhost:3000'], - enableDnsRebindingProtection: true - }); - await transport.start(); - - const mockReq = createMockRequest({ - headers: { - host: 'evil.com', - 'content-type': 'application/json' - } - }); - const mockHandleRes = createMockResponse(); - - await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes.writeHead).toHaveBeenCalledWith(403); - expect(mockHandleRes.end).toHaveBeenCalledWith('Invalid Host header: evil.com'); - }); - - it('should reject requests without host header when allowedHosts is configured', async () => { - const mockRes = createMockResponse(); - const transport = new SSEServerTransport('/messages', mockRes, { - allowedHosts: ['localhost:3000'], - enableDnsRebindingProtection: true - }); - await transport.start(); - - const mockReq = createMockRequest({ - headers: { - 'content-type': 'application/json' - } - }); - const mockHandleRes = createMockResponse(); - - await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes.writeHead).toHaveBeenCalledWith(403); - expect(mockHandleRes.end).toHaveBeenCalledWith('Invalid Host header: undefined'); - }); - }); - - describe('Origin header validation', () => { - it('should accept requests with allowed origin headers', async () => { - const mockRes = createMockResponse(); - const transport = new SSEServerTransport('/messages', mockRes, { - allowedOrigins: ['http://localhost:3000', 'https://example.com'], - enableDnsRebindingProtection: true - }); - await transport.start(); - - const mockReq = createMockRequest({ - headers: { - origin: 'http://localhost:3000', - 'content-type': 'application/json' - } - }); - const mockHandleRes = createMockResponse(); - - await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes.writeHead).toHaveBeenCalledWith(202); - expect(mockHandleRes.end).toHaveBeenCalledWith('Accepted'); - }); - - it('should reject requests with disallowed origin headers', async () => { - const mockRes = createMockResponse(); - const transport = new SSEServerTransport('/messages', mockRes, { - allowedOrigins: ['http://localhost:3000'], - enableDnsRebindingProtection: true - }); - await transport.start(); - - const mockReq = createMockRequest({ - headers: { - origin: 'http://evil.com', - 'content-type': 'application/json' - } - }); - const mockHandleRes = createMockResponse(); - - await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes.writeHead).toHaveBeenCalledWith(403); - expect(mockHandleRes.end).toHaveBeenCalledWith('Invalid Origin header: http://evil.com'); - }); - }); - - describe('Content-Type validation', () => { - it('should accept requests with application/json content-type', async () => { - const mockRes = createMockResponse(); - const transport = new SSEServerTransport('/messages', mockRes); - await transport.start(); - - const mockReq = createMockRequest({ - headers: { - 'content-type': 'application/json' - } - }); - const mockHandleRes = createMockResponse(); - - await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes.writeHead).toHaveBeenCalledWith(202); - expect(mockHandleRes.end).toHaveBeenCalledWith('Accepted'); - }); - - it('should accept requests with application/json with charset', async () => { - const mockRes = createMockResponse(); - const transport = new SSEServerTransport('/messages', mockRes); - await transport.start(); - - const mockReq = createMockRequest({ - headers: { - 'content-type': 'application/json; charset=utf-8' - } - }); - const mockHandleRes = createMockResponse(); - - await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes.writeHead).toHaveBeenCalledWith(202); - expect(mockHandleRes.end).toHaveBeenCalledWith('Accepted'); - }); - - it('should reject requests with non-application/json content-type when protection is enabled', async () => { - const mockRes = createMockResponse(); - const transport = new SSEServerTransport('/messages', mockRes); - await transport.start(); - - const mockReq = createMockRequest({ - headers: { - 'content-type': 'text/plain' - } - }); - const mockHandleRes = createMockResponse(); - - await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes.writeHead).toHaveBeenCalledWith(400); - expect(mockHandleRes.end).toHaveBeenCalledWith('Error: Unsupported content-type: text/plain'); - }); - }); - - describe('enableDnsRebindingProtection option', () => { - it('should skip all validations when enableDnsRebindingProtection is false', async () => { - const mockRes = createMockResponse(); - const transport = new SSEServerTransport('/messages', mockRes, { - allowedHosts: ['localhost:3000'], - allowedOrigins: ['http://localhost:3000'], - enableDnsRebindingProtection: false - }); - await transport.start(); - - const mockReq = createMockRequest({ - headers: { - host: 'evil.com', - origin: 'http://evil.com', - 'content-type': 'text/plain' - } - }); - const mockHandleRes = createMockResponse(); - - await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' }); - - // Should pass even with invalid headers because protection is disabled - expect(mockHandleRes.writeHead).toHaveBeenCalledWith(400); - // The error should be from content-type parsing, not DNS rebinding protection - expect(mockHandleRes.end).toHaveBeenCalledWith('Error: Unsupported content-type: text/plain'); - }); - }); - - describe('Combined validations', () => { - it('should validate both host and origin when both are configured', async () => { - const mockRes = createMockResponse(); - const transport = new SSEServerTransport('/messages', mockRes, { - allowedHosts: ['localhost:3000'], - allowedOrigins: ['http://localhost:3000'], - enableDnsRebindingProtection: true - }); - await transport.start(); - - // Valid host, invalid origin - const mockReq1 = createMockRequest({ - headers: { - host: 'localhost:3000', - origin: 'http://evil.com', - 'content-type': 'application/json' - } - }); - const mockHandleRes1 = createMockResponse(); - - await transport.handlePostMessage(mockReq1, mockHandleRes1, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes1.writeHead).toHaveBeenCalledWith(403); - expect(mockHandleRes1.end).toHaveBeenCalledWith('Invalid Origin header: http://evil.com'); - - // Invalid host, valid origin - const mockReq2 = createMockRequest({ - headers: { - host: 'evil.com', - origin: 'http://localhost:3000', - 'content-type': 'application/json' - } - }); - const mockHandleRes2 = createMockResponse(); - - await transport.handlePostMessage(mockReq2, mockHandleRes2, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes2.writeHead).toHaveBeenCalledWith(403); - expect(mockHandleRes2.end).toHaveBeenCalledWith('Invalid Host header: evil.com'); - - // Both valid - const mockReq3 = createMockRequest({ - headers: { - host: 'localhost:3000', - origin: 'http://localhost:3000', - 'content-type': 'application/json' - } - }); - const mockHandleRes3 = createMockResponse(); - - await transport.handlePostMessage(mockReq3, mockHandleRes3, { jsonrpc: '2.0', method: 'test' }); - - expect(mockHandleRes3.writeHead).toHaveBeenCalledWith(202); - expect(mockHandleRes3.end).toHaveBeenCalledWith('Accepted'); - }); - }); - }); -}); diff --git a/typescript-sdk/src/server/sse.ts b/typescript-sdk/src/server/sse.ts deleted file mode 100644 index 3405af7..0000000 --- a/typescript-sdk/src/server/sse.ts +++ /dev/null @@ -1,213 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { IncomingMessage, ServerResponse } from 'node:http'; -import { Transport } from '../shared/transport.js'; -import { JSONRPCMessage, JSONRPCMessageSchema, MessageExtraInfo, RequestInfo } from '../types.js'; -import getRawBody from 'raw-body'; -import contentType from 'content-type'; -import { AuthInfo } from './auth/types.js'; -import { URL } from 'url'; - -const MAXIMUM_MESSAGE_SIZE = '4mb'; - -/** - * Configuration options for SSEServerTransport. - */ -export interface SSEServerTransportOptions { - /** - * List of allowed host header values for DNS rebinding protection. - * If not specified, host validation is disabled. - */ - allowedHosts?: string[]; - - /** - * List of allowed origin header values for DNS rebinding protection. - * If not specified, origin validation is disabled. - */ - allowedOrigins?: string[]; - - /** - * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). - * Default is false for backwards compatibility. - */ - enableDnsRebindingProtection?: boolean; -} - -/** - * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. - * - * This transport is only available in Node.js environments. - */ -export class SSEServerTransport implements Transport { - private _sseResponse?: ServerResponse; - private _sessionId: string; - private _options: SSEServerTransportOptions; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; - - /** - * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. - */ - constructor( - private _endpoint: string, - private res: ServerResponse, - options?: SSEServerTransportOptions - ) { - this._sessionId = randomUUID(); - this._options = options || { enableDnsRebindingProtection: false }; - } - - /** - * Validates request headers for DNS rebinding protection. - * @returns Error message if validation fails, undefined if validation passes. - */ - private validateRequestHeaders(req: IncomingMessage): string | undefined { - // Skip validation if protection is not enabled - if (!this._options.enableDnsRebindingProtection) { - return undefined; - } - - // Validate Host header if allowedHosts is configured - if (this._options.allowedHosts && this._options.allowedHosts.length > 0) { - const hostHeader = req.headers.host; - if (!hostHeader || !this._options.allowedHosts.includes(hostHeader)) { - return `Invalid Host header: ${hostHeader}`; - } - } - - // Validate Origin header if allowedOrigins is configured - if (this._options.allowedOrigins && this._options.allowedOrigins.length > 0) { - const originHeader = req.headers.origin; - if (!originHeader || !this._options.allowedOrigins.includes(originHeader)) { - return `Invalid Origin header: ${originHeader}`; - } - } - - return undefined; - } - - /** - * Handles the initial SSE connection request. - * - * This should be called when a GET request is made to establish the SSE stream. - */ - async start(): Promise { - if (this._sseResponse) { - throw new Error('SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.'); - } - - this.res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }); - - // Send the endpoint event - // Use a dummy base URL because this._endpoint is relative. - // This allows using URL/URLSearchParams for robust parameter handling. - const dummyBase = 'http://localhost'; // Any valid base works - const endpointUrl = new URL(this._endpoint, dummyBase); - endpointUrl.searchParams.set('sessionId', this._sessionId); - - // Reconstruct the relative URL string (pathname + search + hash) - const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash; - - this.res.write(`event: endpoint\ndata: ${relativeUrlWithSession}\n\n`); - - this._sseResponse = this.res; - this.res.on('close', () => { - this._sseResponse = undefined; - this.onclose?.(); - }); - } - - /** - * Handles incoming POST messages. - * - * This should be called when a POST request is made to send a message to the server. - */ - async handlePostMessage(req: IncomingMessage & { auth?: AuthInfo }, res: ServerResponse, parsedBody?: unknown): Promise { - if (!this._sseResponse) { - const message = 'SSE connection not established'; - res.writeHead(500).end(message); - throw new Error(message); - } - - // Validate request headers for DNS rebinding protection - const validationError = this.validateRequestHeaders(req); - if (validationError) { - res.writeHead(403).end(validationError); - this.onerror?.(new Error(validationError)); - return; - } - - const authInfo: AuthInfo | undefined = req.auth; - const requestInfo: RequestInfo = { headers: req.headers }; - - let body: string | unknown; - try { - const ct = contentType.parse(req.headers['content-type'] ?? ''); - if (ct.type !== 'application/json') { - throw new Error(`Unsupported content-type: ${ct.type}`); - } - - body = - parsedBody ?? - (await getRawBody(req, { - limit: MAXIMUM_MESSAGE_SIZE, - encoding: ct.parameters.charset ?? 'utf-8' - })); - } catch (error) { - res.writeHead(400).end(String(error)); - this.onerror?.(error as Error); - return; - } - - try { - await this.handleMessage(typeof body === 'string' ? JSON.parse(body) : body, { requestInfo, authInfo }); - } catch { - res.writeHead(400).end(`Invalid message: ${body}`); - return; - } - - res.writeHead(202).end('Accepted'); - } - - /** - * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. - */ - async handleMessage(message: unknown, extra?: MessageExtraInfo): Promise { - let parsedMessage: JSONRPCMessage; - try { - parsedMessage = JSONRPCMessageSchema.parse(message); - } catch (error) { - this.onerror?.(error as Error); - throw error; - } - - this.onmessage?.(parsedMessage, extra); - } - - async close(): Promise { - this._sseResponse?.end(); - this._sseResponse = undefined; - this.onclose?.(); - } - - async send(message: JSONRPCMessage): Promise { - if (!this._sseResponse) { - throw new Error('Not connected'); - } - - this._sseResponse.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`); - } - - /** - * Returns the session ID for this transport. - * - * This can be used to route incoming POST requests. - */ - get sessionId(): string { - return this._sessionId; - } -} diff --git a/typescript-sdk/src/server/stdio.test.ts b/typescript-sdk/src/server/stdio.test.ts deleted file mode 100644 index 7d5d5c1..0000000 --- a/typescript-sdk/src/server/stdio.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { Readable, Writable } from 'node:stream'; -import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; -import { JSONRPCMessage } from '../types.js'; -import { StdioServerTransport } from './stdio.js'; - -let input: Readable; -let outputBuffer: ReadBuffer; -let output: Writable; - -beforeEach(() => { - input = new Readable({ - // We'll use input.push() instead. - read: () => {} - }); - - outputBuffer = new ReadBuffer(); - output = new Writable({ - write(chunk, encoding, callback) { - outputBuffer.append(chunk); - callback(); - } - }); -}); - -test('should start then close cleanly', async () => { - const server = new StdioServerTransport(input, output); - server.onerror = error => { - throw error; - }; - - let didClose = false; - server.onclose = () => { - didClose = true; - }; - - await server.start(); - expect(didClose).toBeFalsy(); - await server.close(); - expect(didClose).toBeTruthy(); -}); - -test('should not read until started', async () => { - const server = new StdioServerTransport(input, output); - server.onerror = error => { - throw error; - }; - - let didRead = false; - const readMessage = new Promise(resolve => { - server.onmessage = message => { - didRead = true; - resolve(message); - }; - }); - - const message: JSONRPCMessage = { - jsonrpc: '2.0', - id: 1, - method: 'ping' - }; - input.push(serializeMessage(message)); - - expect(didRead).toBeFalsy(); - await server.start(); - expect(await readMessage).toEqual(message); -}); - -test('should read multiple messages', async () => { - const server = new StdioServerTransport(input, output); - server.onerror = error => { - throw error; - }; - - const messages: JSONRPCMessage[] = [ - { - jsonrpc: '2.0', - id: 1, - method: 'ping' - }, - { - jsonrpc: '2.0', - method: 'notifications/initialized' - } - ]; - - const readMessages: JSONRPCMessage[] = []; - const finished = new Promise(resolve => { - server.onmessage = message => { - readMessages.push(message); - if (JSON.stringify(message) === JSON.stringify(messages[1])) { - resolve(); - } - }; - }); - - input.push(serializeMessage(messages[0])); - input.push(serializeMessage(messages[1])); - - await server.start(); - await finished; - expect(readMessages).toEqual(messages); -}); diff --git a/typescript-sdk/src/server/stdio.ts b/typescript-sdk/src/server/stdio.ts deleted file mode 100644 index ece9d0a..0000000 --- a/typescript-sdk/src/server/stdio.ts +++ /dev/null @@ -1,92 +0,0 @@ -import process from 'node:process'; -import { Readable, Writable } from 'node:stream'; -import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; -import { JSONRPCMessage } from '../types.js'; -import { Transport } from '../shared/transport.js'; - -/** - * Server transport for stdio: this communicates with a MCP client by reading from the current process' stdin and writing to stdout. - * - * This transport is only available in Node.js environments. - */ -export class StdioServerTransport implements Transport { - private _readBuffer: ReadBuffer = new ReadBuffer(); - private _started = false; - - constructor( - private _stdin: Readable = process.stdin, - private _stdout: Writable = process.stdout - ) {} - - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - - // Arrow functions to bind `this` properly, while maintaining function identity. - _ondata = (chunk: Buffer) => { - this._readBuffer.append(chunk); - this.processReadBuffer(); - }; - _onerror = (error: Error) => { - this.onerror?.(error); - }; - - /** - * Starts listening for messages on stdin. - */ - async start(): Promise { - if (this._started) { - throw new Error( - 'StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.' - ); - } - - this._started = true; - this._stdin.on('data', this._ondata); - this._stdin.on('error', this._onerror); - } - - private processReadBuffer() { - while (true) { - try { - const message = this._readBuffer.readMessage(); - if (message === null) { - break; - } - - this.onmessage?.(message); - } catch (error) { - this.onerror?.(error as Error); - } - } - } - - async close(): Promise { - // Remove our event listeners first - this._stdin.off('data', this._ondata); - this._stdin.off('error', this._onerror); - - // Check if we were the only data listener - const remainingDataListeners = this._stdin.listenerCount('data'); - if (remainingDataListeners === 0) { - // Only pause stdin if we were the only listener - // This prevents interfering with other parts of the application that might be using stdin - this._stdin.pause(); - } - - // Clear the buffer and notify closure - this._readBuffer.clear(); - this.onclose?.(); - } - - send(message: JSONRPCMessage): Promise { - return new Promise(resolve => { - const json = serializeMessage(message); - if (this._stdout.write(json)) { - resolve(); - } else { - this._stdout.once('drain', resolve); - } - }); - } -} diff --git a/typescript-sdk/src/server/streamableHttp.test.ts b/typescript-sdk/src/server/streamableHttp.test.ts deleted file mode 100644 index 824d0f4..0000000 --- a/typescript-sdk/src/server/streamableHttp.test.ts +++ /dev/null @@ -1,2148 +0,0 @@ -import { createServer, type Server, IncomingMessage, ServerResponse } from 'node:http'; -import { createServer as netCreateServer, AddressInfo } from 'node:net'; -import { randomUUID } from 'node:crypto'; -import { EventStore, StreamableHTTPServerTransport, EventId, StreamId } from './streamableHttp.js'; -import { McpServer } from './mcp.js'; -import { CallToolResult, JSONRPCMessage } from '../types.js'; -import { z } from 'zod'; -import { AuthInfo } from './auth/types.js'; - -async function getFreePort() { - return new Promise(res => { - const srv = netCreateServer(); - srv.listen(0, () => { - const address = srv.address()!; - if (typeof address === 'string') { - throw new Error('Unexpected address type: ' + typeof address); - } - const port = (address as AddressInfo).port; - srv.close(_err => res(port)); - }); - }); -} - -/** - * Test server configuration for StreamableHTTPServerTransport tests - */ -interface TestServerConfig { - sessionIdGenerator: (() => string) | undefined; - enableJsonResponse?: boolean; - customRequestHandler?: (req: IncomingMessage, res: ServerResponse, parsedBody?: unknown) => Promise; - eventStore?: EventStore; - onsessioninitialized?: (sessionId: string) => void | Promise; - onsessionclosed?: (sessionId: string) => void | Promise; -} - -/** - * Helper to create and start test HTTP server with MCP setup - */ -async function createTestServer(config: TestServerConfig = { sessionIdGenerator: () => randomUUID() }): Promise<{ - server: Server; - transport: StreamableHTTPServerTransport; - mcpServer: McpServer; - baseUrl: URL; -}> { - const mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: { logging: {} } }); - - mcpServer.tool( - 'greet', - 'A simple greeting tool', - { name: z.string().describe('Name to greet') }, - async ({ name }): Promise => { - return { content: [{ type: 'text', text: `Hello, ${name}!` }] }; - } - ); - - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: config.sessionIdGenerator, - enableJsonResponse: config.enableJsonResponse ?? false, - eventStore: config.eventStore, - onsessioninitialized: config.onsessioninitialized, - onsessionclosed: config.onsessionclosed - }); - - await mcpServer.connect(transport); - - const server = createServer(async (req, res) => { - try { - if (config.customRequestHandler) { - await config.customRequestHandler(req, res); - } else { - await transport.handleRequest(req, res); - } - } catch (error) { - console.error('Error handling request:', error); - if (!res.headersSent) res.writeHead(500).end(); - } - }); - - const baseUrl = await new Promise(resolve => { - server.listen(0, '127.0.0.1', () => { - const addr = server.address() as AddressInfo; - resolve(new URL(`http://127.0.0.1:${addr.port}`)); - }); - }); - - return { server, transport, mcpServer, baseUrl }; -} - -/** - * Helper to create and start authenticated test HTTP server with MCP setup - */ -async function createTestAuthServer(config: TestServerConfig = { sessionIdGenerator: () => randomUUID() }): Promise<{ - server: Server; - transport: StreamableHTTPServerTransport; - mcpServer: McpServer; - baseUrl: URL; -}> { - const mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: { logging: {} } }); - - mcpServer.tool( - 'profile', - 'A user profile data tool', - { active: z.boolean().describe('Profile status') }, - async ({ active }, { authInfo }): Promise => { - return { content: [{ type: 'text', text: `${active ? 'Active' : 'Inactive'} profile from token: ${authInfo?.token}!` }] }; - } - ); - - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: config.sessionIdGenerator, - enableJsonResponse: config.enableJsonResponse ?? false, - eventStore: config.eventStore, - onsessioninitialized: config.onsessioninitialized, - onsessionclosed: config.onsessionclosed - }); - - await mcpServer.connect(transport); - - const server = createServer(async (req: IncomingMessage & { auth?: AuthInfo }, res) => { - try { - if (config.customRequestHandler) { - await config.customRequestHandler(req, res); - } else { - req.auth = { token: req.headers['authorization']?.split(' ')[1] } as AuthInfo; - await transport.handleRequest(req, res); - } - } catch (error) { - console.error('Error handling request:', error); - if (!res.headersSent) res.writeHead(500).end(); - } - }); - - const baseUrl = await new Promise(resolve => { - server.listen(0, '127.0.0.1', () => { - const addr = server.address() as AddressInfo; - resolve(new URL(`http://127.0.0.1:${addr.port}`)); - }); - }); - - return { server, transport, mcpServer, baseUrl }; -} - -/** - * Helper to stop test server - */ -async function stopTestServer({ server, transport }: { server: Server; transport: StreamableHTTPServerTransport }): Promise { - // First close the transport to ensure all SSE streams are closed - await transport.close(); - - // Close the server without waiting indefinitely - server.close(); -} - -/** - * Common test messages - */ -const TEST_MESSAGES = { - initialize: { - jsonrpc: '2.0', - method: 'initialize', - params: { - clientInfo: { name: 'test-client', version: '1.0' }, - protocolVersion: '2025-03-26', - capabilities: {} - }, - - id: 'init-1' - } as JSONRPCMessage, - - toolsList: { - jsonrpc: '2.0', - method: 'tools/list', - params: {}, - id: 'tools-1' - } as JSONRPCMessage -}; - -/** - * Helper to extract text from SSE response - * Note: Can only be called once per response stream. For multiple reads, - * get the reader manually and read multiple times. - */ -async function readSSEEvent(response: Response): Promise { - const reader = response.body?.getReader(); - const { value } = await reader!.read(); - return new TextDecoder().decode(value); -} - -/** - * Helper to send JSON-RPC request - */ -async function sendPostRequest( - baseUrl: URL, - message: JSONRPCMessage | JSONRPCMessage[], - sessionId?: string, - extraHeaders?: Record -): Promise { - const headers: Record = { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - ...extraHeaders - }; - - if (sessionId) { - headers['mcp-session-id'] = sessionId; - // After initialization, include the protocol version header - headers['mcp-protocol-version'] = '2025-03-26'; - } - - return fetch(baseUrl, { - method: 'POST', - headers, - body: JSON.stringify(message) - }); -} - -function expectErrorResponse(data: unknown, expectedCode: number, expectedMessagePattern: RegExp): void { - expect(data).toMatchObject({ - jsonrpc: '2.0', - error: expect.objectContaining({ - code: expectedCode, - message: expect.stringMatching(expectedMessagePattern) - }) - }); -} - -describe('StreamableHTTPServerTransport', () => { - let server: Server; - let mcpServer: McpServer; - let transport: StreamableHTTPServerTransport; - let baseUrl: URL; - let sessionId: string; - - beforeEach(async () => { - const result = await createTestServer(); - server = result.server; - transport = result.transport; - mcpServer = result.mcpServer; - baseUrl = result.baseUrl; - }); - - afterEach(async () => { - await stopTestServer({ server, transport }); - }); - - async function initializeServer(): Promise { - const response = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); - - expect(response.status).toBe(200); - const newSessionId = response.headers.get('mcp-session-id'); - expect(newSessionId).toBeDefined(); - return newSessionId as string; - } - - it('should initialize server and generate session ID', async () => { - const response = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); - - expect(response.status).toBe(200); - expect(response.headers.get('content-type')).toBe('text/event-stream'); - expect(response.headers.get('mcp-session-id')).toBeDefined(); - }); - - it('should reject second initialization request', async () => { - // First initialize - const sessionId = await initializeServer(); - expect(sessionId).toBeDefined(); - - // Try second initialize - const secondInitMessage = { - ...TEST_MESSAGES.initialize, - id: 'second-init' - }; - - const response = await sendPostRequest(baseUrl, secondInitMessage); - - expect(response.status).toBe(400); - const errorData = await response.json(); - expectErrorResponse(errorData, -32600, /Server already initialized/); - }); - - it('should reject batch initialize request', async () => { - const batchInitMessages: JSONRPCMessage[] = [ - TEST_MESSAGES.initialize, - { - jsonrpc: '2.0', - method: 'initialize', - params: { - clientInfo: { name: 'test-client-2', version: '1.0' }, - protocolVersion: '2025-03-26' - }, - id: 'init-2' - } - ]; - - const response = await sendPostRequest(baseUrl, batchInitMessages); - - expect(response.status).toBe(400); - const errorData = await response.json(); - expectErrorResponse(errorData, -32600, /Only one initialization request is allowed/); - }); - - it('should handle post requests via sse response correctly', async () => { - sessionId = await initializeServer(); - - const response = await sendPostRequest(baseUrl, TEST_MESSAGES.toolsList, sessionId); - - expect(response.status).toBe(200); - - // Read the SSE stream for the response - const text = await readSSEEvent(response); - - // Parse the SSE event - const eventLines = text.split('\n'); - const dataLine = eventLines.find(line => line.startsWith('data:')); - expect(dataLine).toBeDefined(); - - const eventData = JSON.parse(dataLine!.substring(5)); - expect(eventData).toMatchObject({ - jsonrpc: '2.0', - result: expect.objectContaining({ - tools: expect.arrayContaining([ - expect.objectContaining({ - name: 'greet', - description: 'A simple greeting tool' - }) - ]) - }), - id: 'tools-1' - }); - }); - - it('should call a tool and return the result', async () => { - sessionId = await initializeServer(); - - const toolCallMessage: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'tools/call', - params: { - name: 'greet', - arguments: { - name: 'Test User' - } - }, - id: 'call-1' - }; - - const response = await sendPostRequest(baseUrl, toolCallMessage, sessionId); - expect(response.status).toBe(200); - - const text = await readSSEEvent(response); - const eventLines = text.split('\n'); - const dataLine = eventLines.find(line => line.startsWith('data:')); - expect(dataLine).toBeDefined(); - - const eventData = JSON.parse(dataLine!.substring(5)); - expect(eventData).toMatchObject({ - jsonrpc: '2.0', - result: { - content: [ - { - type: 'text', - text: 'Hello, Test User!' - } - ] - }, - id: 'call-1' - }); - }); - - /*** - * Test: Tool With Request Info - */ - it('should pass request info to tool callback', async () => { - sessionId = await initializeServer(); - - mcpServer.tool( - 'test-request-info', - 'A simple test tool with request info', - { name: z.string().describe('Name to greet') }, - async ({ name }, { requestInfo }): Promise => { - return { - content: [ - { type: 'text', text: `Hello, ${name}!` }, - { type: 'text', text: `${JSON.stringify(requestInfo)}` } - ] - }; - } - ); - - const toolCallMessage: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'tools/call', - params: { - name: 'test-request-info', - arguments: { - name: 'Test User' - } - }, - id: 'call-1' - }; - - const response = await sendPostRequest(baseUrl, toolCallMessage, sessionId); - expect(response.status).toBe(200); - - const text = await readSSEEvent(response); - const eventLines = text.split('\n'); - const dataLine = eventLines.find(line => line.startsWith('data:')); - expect(dataLine).toBeDefined(); - - const eventData = JSON.parse(dataLine!.substring(5)); - - expect(eventData).toMatchObject({ - jsonrpc: '2.0', - result: { - content: [ - { type: 'text', text: 'Hello, Test User!' }, - { type: 'text', text: expect.any(String) } - ] - }, - id: 'call-1' - }); - - const requestInfo = JSON.parse(eventData.result.content[1].text); - expect(requestInfo).toMatchObject({ - headers: { - 'content-type': 'application/json', - accept: 'application/json, text/event-stream', - connection: 'keep-alive', - 'mcp-session-id': sessionId, - 'accept-language': '*', - 'user-agent': expect.any(String), - 'accept-encoding': expect.any(String), - 'content-length': expect.any(String) - } - }); - }); - - it('should reject requests without a valid session ID', async () => { - const response = await sendPostRequest(baseUrl, TEST_MESSAGES.toolsList); - - expect(response.status).toBe(400); - const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Bad Request/); - expect(errorData.id).toBeNull(); - }); - - it('should reject invalid session ID', async () => { - // First initialize to be in valid state - await initializeServer(); - - // Now try with invalid session ID - const response = await sendPostRequest(baseUrl, TEST_MESSAGES.toolsList, 'invalid-session-id'); - - expect(response.status).toBe(404); - const errorData = await response.json(); - expectErrorResponse(errorData, -32001, /Session not found/); - }); - - it('should establish standalone SSE stream and receive server-initiated messages', async () => { - // First initialize to get a session ID - sessionId = await initializeServer(); - - // Open a standalone SSE stream - const sseResponse = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(sseResponse.status).toBe(200); - expect(sseResponse.headers.get('content-type')).toBe('text/event-stream'); - - // Send a notification (server-initiated message) that should appear on SSE stream - const notification: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'notifications/message', - params: { level: 'info', data: 'Test notification' } - }; - - // Send the notification via transport - await transport.send(notification); - - // Read from the stream and verify we got the notification - const text = await readSSEEvent(sseResponse); - - const eventLines = text.split('\n'); - const dataLine = eventLines.find(line => line.startsWith('data:')); - expect(dataLine).toBeDefined(); - - const eventData = JSON.parse(dataLine!.substring(5)); - expect(eventData).toMatchObject({ - jsonrpc: '2.0', - method: 'notifications/message', - params: { level: 'info', data: 'Test notification' } - }); - }); - - it('should not close GET SSE stream after sending multiple server notifications', async () => { - sessionId = await initializeServer(); - - // Open a standalone SSE stream - const sseResponse = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(sseResponse.status).toBe(200); - const reader = sseResponse.body?.getReader(); - - // Send multiple notifications - const notification1: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'notifications/message', - params: { level: 'info', data: 'First notification' } - }; - - // Just send one and verify it comes through - then the stream should stay open - await transport.send(notification1); - - const { value, done } = await reader!.read(); - const text = new TextDecoder().decode(value); - expect(text).toContain('First notification'); - expect(done).toBe(false); // Stream should still be open - }); - - it('should reject second SSE stream for the same session', async () => { - sessionId = await initializeServer(); - - // Open first SSE stream - const firstStream = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(firstStream.status).toBe(200); - - // Try to open a second SSE stream with the same session ID - const secondStream = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-03-26' - } - }); - - // Should be rejected - expect(secondStream.status).toBe(409); // Conflict - const errorData = await secondStream.json(); - expectErrorResponse(errorData, -32000, /Only one SSE stream is allowed per session/); - }); - - it('should reject GET requests without Accept: text/event-stream header', async () => { - sessionId = await initializeServer(); - - // Try GET without proper Accept header - const response = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'application/json', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(response.status).toBe(406); - const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Client must accept text\/event-stream/); - }); - - it('should reject POST requests without proper Accept header', async () => { - sessionId = await initializeServer(); - - // Try POST without Accept: text/event-stream - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json', // Missing text/event-stream - 'mcp-session-id': sessionId - }, - body: JSON.stringify(TEST_MESSAGES.toolsList) - }); - - expect(response.status).toBe(406); - const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Client must accept both application\/json and text\/event-stream/); - }); - - it('should reject unsupported Content-Type', async () => { - sessionId = await initializeServer(); - - // Try POST with text/plain Content-Type - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'text/plain', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': sessionId - }, - body: 'This is plain text' - }); - - expect(response.status).toBe(415); - const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Content-Type must be application\/json/); - }); - - it('should handle JSON-RPC batch notification messages with 202 response', async () => { - sessionId = await initializeServer(); - - // Send batch of notifications (no IDs) - const batchNotifications: JSONRPCMessage[] = [ - { jsonrpc: '2.0', method: 'someNotification1', params: {} }, - { jsonrpc: '2.0', method: 'someNotification2', params: {} } - ]; - const response = await sendPostRequest(baseUrl, batchNotifications, sessionId); - - expect(response.status).toBe(202); - }); - - it('should handle batch request messages with SSE stream for responses', async () => { - sessionId = await initializeServer(); - - // Send batch of requests - const batchRequests: JSONRPCMessage[] = [ - { jsonrpc: '2.0', method: 'tools/list', params: {}, id: 'req-1' }, - { jsonrpc: '2.0', method: 'tools/call', params: { name: 'greet', arguments: { name: 'BatchUser' } }, id: 'req-2' } - ]; - const response = await sendPostRequest(baseUrl, batchRequests, sessionId); - - expect(response.status).toBe(200); - expect(response.headers.get('content-type')).toBe('text/event-stream'); - - const reader = response.body?.getReader(); - - // The responses may come in any order or together in one chunk - const { value } = await reader!.read(); - const text = new TextDecoder().decode(value); - - // Check that both responses were sent on the same stream - expect(text).toContain('"id":"req-1"'); - expect(text).toContain('"tools"'); // tools/list result - expect(text).toContain('"id":"req-2"'); - expect(text).toContain('Hello, BatchUser'); // tools/call result - }); - - it('should properly handle invalid JSON data', async () => { - sessionId = await initializeServer(); - - // Send invalid JSON - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': sessionId - }, - body: 'This is not valid JSON' - }); - - expect(response.status).toBe(400); - const errorData = await response.json(); - expectErrorResponse(errorData, -32700, /Parse error/); - }); - - it('should return 400 error for invalid JSON-RPC messages', async () => { - sessionId = await initializeServer(); - - // Invalid JSON-RPC (missing required jsonrpc version) - const invalidMessage = { method: 'tools/list', params: {}, id: 1 }; // missing jsonrpc version - const response = await sendPostRequest(baseUrl, invalidMessage as JSONRPCMessage, sessionId); - - expect(response.status).toBe(400); - const errorData = await response.json(); - expect(errorData).toMatchObject({ - jsonrpc: '2.0', - error: expect.anything() - }); - }); - - it('should reject requests to uninitialized server', async () => { - // Create a new HTTP server and transport without initializing - const { server: uninitializedServer, transport: uninitializedTransport, baseUrl: uninitializedUrl } = await createTestServer(); - // Transport not used in test but needed for cleanup - - // No initialization, just send a request directly - const uninitializedMessage: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'tools/list', - params: {}, - id: 'uninitialized-test' - }; - - // Send a request to uninitialized server - const response = await sendPostRequest(uninitializedUrl, uninitializedMessage, 'any-session-id'); - - expect(response.status).toBe(400); - const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Server not initialized/); - - // Cleanup - await stopTestServer({ server: uninitializedServer, transport: uninitializedTransport }); - }); - - it('should send response messages to the connection that sent the request', async () => { - sessionId = await initializeServer(); - - const message1: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'tools/list', - params: {}, - id: 'req-1' - }; - - const message2: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'tools/call', - params: { - name: 'greet', - arguments: { name: 'Connection2' } - }, - id: 'req-2' - }; - - // Make two concurrent fetch connections for different requests - const req1 = sendPostRequest(baseUrl, message1, sessionId); - const req2 = sendPostRequest(baseUrl, message2, sessionId); - - // Get both responses - const [response1, response2] = await Promise.all([req1, req2]); - const reader1 = response1.body?.getReader(); - const reader2 = response2.body?.getReader(); - - // Read responses from each stream (requires each receives its specific response) - const { value: value1 } = await reader1!.read(); - const text1 = new TextDecoder().decode(value1); - expect(text1).toContain('"id":"req-1"'); - expect(text1).toContain('"tools"'); // tools/list result - - const { value: value2 } = await reader2!.read(); - const text2 = new TextDecoder().decode(value2); - expect(text2).toContain('"id":"req-2"'); - expect(text2).toContain('Hello, Connection2'); // tools/call result - }); - - it('should keep stream open after sending server notifications', async () => { - sessionId = await initializeServer(); - - // Open a standalone SSE stream - const sseResponse = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-03-26' - } - }); - - // Send several server-initiated notifications - await transport.send({ - jsonrpc: '2.0', - method: 'notifications/message', - params: { level: 'info', data: 'First notification' } - }); - - await transport.send({ - jsonrpc: '2.0', - method: 'notifications/message', - params: { level: 'info', data: 'Second notification' } - }); - - // Stream should still be open - it should not close after sending notifications - expect(sseResponse.bodyUsed).toBe(false); - }); - - // The current implementation will close the entire transport for DELETE - // Creating a temporary transport/server where we don't care if it gets closed - it('should properly handle DELETE requests and close session', async () => { - // Setup a temporary server for this test - const tempResult = await createTestServer(); - const tempServer = tempResult.server; - const tempUrl = tempResult.baseUrl; - - // Initialize to get a session ID - const initResponse = await sendPostRequest(tempUrl, TEST_MESSAGES.initialize); - const tempSessionId = initResponse.headers.get('mcp-session-id'); - - // Now DELETE the session - const deleteResponse = await fetch(tempUrl, { - method: 'DELETE', - headers: { - 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(deleteResponse.status).toBe(200); - - // Clean up - don't wait indefinitely for server close - tempServer.close(); - }); - - it('should reject DELETE requests with invalid session ID', async () => { - // Initialize the server first to activate it - sessionId = await initializeServer(); - - // Try to delete with invalid session ID - const response = await fetch(baseUrl, { - method: 'DELETE', - headers: { - 'mcp-session-id': 'invalid-session-id', - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(response.status).toBe(404); - const errorData = await response.json(); - expectErrorResponse(errorData, -32001, /Session not found/); - }); - - describe('protocol version header validation', () => { - it('should accept requests with matching protocol version', async () => { - sessionId = await initializeServer(); - - // Send request with matching protocol version - const response = await sendPostRequest(baseUrl, TEST_MESSAGES.toolsList, sessionId); - - expect(response.status).toBe(200); - }); - - it('should accept requests without protocol version header', async () => { - sessionId = await initializeServer(); - - // Send request without protocol version header - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': sessionId - // No mcp-protocol-version header - }, - body: JSON.stringify(TEST_MESSAGES.toolsList) - }); - - expect(response.status).toBe(200); - }); - - it('should reject requests with unsupported protocol version', async () => { - sessionId = await initializeServer(); - - // Send request with unsupported protocol version - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '1999-01-01' // Unsupported version - }, - body: JSON.stringify(TEST_MESSAGES.toolsList) - }); - - expect(response.status).toBe(400); - const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Bad Request: Unsupported protocol version \(supported versions: .+\)/); - }); - - it('should accept when protocol version differs from negotiated version', async () => { - sessionId = await initializeServer(); - - // Spy on console.warn to verify warning is logged - const warnSpy = jest.spyOn(console, 'warn').mockImplementation(); - - // Send request with different but supported protocol version - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2024-11-05' // Different but supported version - }, - body: JSON.stringify(TEST_MESSAGES.toolsList) - }); - - // Request should still succeed - expect(response.status).toBe(200); - - warnSpy.mockRestore(); - }); - - it('should handle protocol version validation for GET requests', async () => { - sessionId = await initializeServer(); - - // GET request with unsupported protocol version - const response = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': 'invalid-version' - } - }); - - expect(response.status).toBe(400); - const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Bad Request: Unsupported protocol version \(supported versions: .+\)/); - }); - - it('should handle protocol version validation for DELETE requests', async () => { - sessionId = await initializeServer(); - - // DELETE request with unsupported protocol version - const response = await fetch(baseUrl, { - method: 'DELETE', - headers: { - 'mcp-session-id': sessionId, - 'mcp-protocol-version': 'invalid-version' - } - }); - - expect(response.status).toBe(400); - const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Bad Request: Unsupported protocol version \(supported versions: .+\)/); - }); - }); -}); - -describe('StreamableHTTPServerTransport with AuthInfo', () => { - let server: Server; - let transport: StreamableHTTPServerTransport; - let baseUrl: URL; - let sessionId: string; - - beforeEach(async () => { - const result = await createTestAuthServer(); - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - }); - - afterEach(async () => { - await stopTestServer({ server, transport }); - }); - - async function initializeServer(): Promise { - const response = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); - - expect(response.status).toBe(200); - const newSessionId = response.headers.get('mcp-session-id'); - expect(newSessionId).toBeDefined(); - return newSessionId as string; - } - - it('should call a tool with authInfo', async () => { - sessionId = await initializeServer(); - - const toolCallMessage: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'tools/call', - params: { - name: 'profile', - arguments: { active: true } - }, - id: 'call-1' - }; - - const response = await sendPostRequest(baseUrl, toolCallMessage, sessionId, { authorization: 'Bearer test-token' }); - expect(response.status).toBe(200); - - const text = await readSSEEvent(response); - const eventLines = text.split('\n'); - const dataLine = eventLines.find(line => line.startsWith('data:')); - expect(dataLine).toBeDefined(); - - const eventData = JSON.parse(dataLine!.substring(5)); - expect(eventData).toMatchObject({ - jsonrpc: '2.0', - result: { - content: [ - { - type: 'text', - text: 'Active profile from token: test-token!' - } - ] - }, - id: 'call-1' - }); - }); - - it('should calls tool without authInfo when it is optional', async () => { - sessionId = await initializeServer(); - - const toolCallMessage: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'tools/call', - params: { - name: 'profile', - arguments: { active: false } - }, - id: 'call-1' - }; - - const response = await sendPostRequest(baseUrl, toolCallMessage, sessionId); - expect(response.status).toBe(200); - - const text = await readSSEEvent(response); - const eventLines = text.split('\n'); - const dataLine = eventLines.find(line => line.startsWith('data:')); - expect(dataLine).toBeDefined(); - - const eventData = JSON.parse(dataLine!.substring(5)); - expect(eventData).toMatchObject({ - jsonrpc: '2.0', - result: { - content: [ - { - type: 'text', - text: 'Inactive profile from token: undefined!' - } - ] - }, - id: 'call-1' - }); - }); -}); - -// Test JSON Response Mode -describe('StreamableHTTPServerTransport with JSON Response Mode', () => { - let server: Server; - let transport: StreamableHTTPServerTransport; - let baseUrl: URL; - let sessionId: string; - - beforeEach(async () => { - const result = await createTestServer({ sessionIdGenerator: () => randomUUID(), enableJsonResponse: true }); - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - - // Initialize and get session ID - const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); - - sessionId = initResponse.headers.get('mcp-session-id') as string; - }); - - afterEach(async () => { - await stopTestServer({ server, transport }); - }); - - it('should return JSON response for a single request', async () => { - const toolsListMessage: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'tools/list', - params: {}, - id: 'json-req-1' - }; - - const response = await sendPostRequest(baseUrl, toolsListMessage, sessionId); - - expect(response.status).toBe(200); - expect(response.headers.get('content-type')).toBe('application/json'); - - const result = await response.json(); - expect(result).toMatchObject({ - jsonrpc: '2.0', - result: expect.objectContaining({ - tools: expect.arrayContaining([expect.objectContaining({ name: 'greet' })]) - }), - id: 'json-req-1' - }); - }); - - it('should return JSON response for batch requests', async () => { - const batchMessages: JSONRPCMessage[] = [ - { jsonrpc: '2.0', method: 'tools/list', params: {}, id: 'batch-1' }, - { jsonrpc: '2.0', method: 'tools/call', params: { name: 'greet', arguments: { name: 'JSON' } }, id: 'batch-2' } - ]; - - const response = await sendPostRequest(baseUrl, batchMessages, sessionId); - - expect(response.status).toBe(200); - expect(response.headers.get('content-type')).toBe('application/json'); - - const results = await response.json(); - expect(Array.isArray(results)).toBe(true); - expect(results).toHaveLength(2); - - // Batch responses can come in any order - const listResponse = results.find((r: { id?: string }) => r.id === 'batch-1'); - const callResponse = results.find((r: { id?: string }) => r.id === 'batch-2'); - - expect(listResponse).toEqual( - expect.objectContaining({ - jsonrpc: '2.0', - id: 'batch-1', - result: expect.objectContaining({ - tools: expect.arrayContaining([expect.objectContaining({ name: 'greet' })]) - }) - }) - ); - - expect(callResponse).toEqual( - expect.objectContaining({ - jsonrpc: '2.0', - id: 'batch-2', - result: expect.objectContaining({ - content: expect.arrayContaining([expect.objectContaining({ type: 'text', text: 'Hello, JSON!' })]) - }) - }) - ); - }); -}); - -// Test pre-parsed body handling -describe('StreamableHTTPServerTransport with pre-parsed body', () => { - let server: Server; - let transport: StreamableHTTPServerTransport; - let baseUrl: URL; - let sessionId: string; - let parsedBody: unknown = null; - - beforeEach(async () => { - const result = await createTestServer({ - customRequestHandler: async (req, res) => { - try { - if (parsedBody !== null) { - await transport.handleRequest(req, res, parsedBody); - parsedBody = null; // Reset after use - } else { - await transport.handleRequest(req, res); - } - } catch (error) { - console.error('Error handling request:', error); - if (!res.headersSent) res.writeHead(500).end(); - } - }, - sessionIdGenerator: () => randomUUID() - }); - - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - - // Initialize and get session ID - const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); - sessionId = initResponse.headers.get('mcp-session-id') as string; - }); - - afterEach(async () => { - await stopTestServer({ server, transport }); - }); - - it('should accept pre-parsed request body', async () => { - // Set up the pre-parsed body - parsedBody = { - jsonrpc: '2.0', - method: 'tools/list', - params: {}, - id: 'preparsed-1' - }; - - // Send an empty body since we'll use pre-parsed body - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': sessionId - }, - // Empty body - we're testing pre-parsed body - body: '' - }); - - expect(response.status).toBe(200); - expect(response.headers.get('content-type')).toBe('text/event-stream'); - - const reader = response.body?.getReader(); - const { value } = await reader!.read(); - const text = new TextDecoder().decode(value); - - // Verify the response used the pre-parsed body - expect(text).toContain('"id":"preparsed-1"'); - expect(text).toContain('"tools"'); - }); - - it('should handle pre-parsed batch messages', async () => { - parsedBody = [ - { jsonrpc: '2.0', method: 'tools/list', params: {}, id: 'batch-1' }, - { jsonrpc: '2.0', method: 'tools/call', params: { name: 'greet', arguments: { name: 'PreParsed' } }, id: 'batch-2' } - ]; - - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': sessionId - }, - body: '' // Empty as we're using pre-parsed - }); - - expect(response.status).toBe(200); - - const reader = response.body?.getReader(); - const { value } = await reader!.read(); - const text = new TextDecoder().decode(value); - - expect(text).toContain('"id":"batch-1"'); - expect(text).toContain('"tools"'); - }); - - it('should prefer pre-parsed body over request body', async () => { - // Set pre-parsed to tools/list - parsedBody = { - jsonrpc: '2.0', - method: 'tools/list', - params: {}, - id: 'preparsed-wins' - }; - - // Send actual body with tools/call - should be ignored - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': sessionId - }, - body: JSON.stringify({ - jsonrpc: '2.0', - method: 'tools/call', - params: { name: 'greet', arguments: { name: 'Ignored' } }, - id: 'ignored-id' - }) - }); - - expect(response.status).toBe(200); - - const reader = response.body?.getReader(); - const { value } = await reader!.read(); - const text = new TextDecoder().decode(value); - - // Should have processed the pre-parsed body - expect(text).toContain('"id":"preparsed-wins"'); - expect(text).toContain('"tools"'); - expect(text).not.toContain('"ignored-id"'); - }); -}); - -// Test resumability support -describe('StreamableHTTPServerTransport with resumability', () => { - let server: Server; - let transport: StreamableHTTPServerTransport; - let baseUrl: URL; - let sessionId: string; - let mcpServer: McpServer; - const storedEvents: Map = new Map(); - - // Simple implementation of EventStore - const eventStore: EventStore = { - async storeEvent(streamId: string, message: JSONRPCMessage): Promise { - const eventId = `${streamId}_${randomUUID()}`; - storedEvents.set(eventId, { eventId, message }); - return eventId; - }, - - async replayEventsAfter( - lastEventId: EventId, - { - send - }: { - send: (eventId: EventId, message: JSONRPCMessage) => Promise; - } - ): Promise { - const streamId = lastEventId.split('_')[0]; - // Extract stream ID from the event ID - // For test simplicity, just return all events with matching streamId that aren't the lastEventId - for (const [eventId, { message }] of storedEvents.entries()) { - if (eventId.startsWith(streamId) && eventId !== lastEventId) { - await send(eventId, message); - } - } - return streamId; - } - }; - - beforeEach(async () => { - storedEvents.clear(); - const result = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - eventStore - }); - - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - mcpServer = result.mcpServer; - - // Verify resumability is enabled on the transport - expect(transport['_eventStore']).toBeDefined(); - - // Initialize the server - const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); - sessionId = initResponse.headers.get('mcp-session-id') as string; - expect(sessionId).toBeDefined(); - }); - - afterEach(async () => { - await stopTestServer({ server, transport }); - storedEvents.clear(); - }); - - it('should store and include event IDs in server SSE messages', async () => { - // Open a standalone SSE stream - const sseResponse = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(sseResponse.status).toBe(200); - expect(sseResponse.headers.get('content-type')).toBe('text/event-stream'); - - // Send a notification that should be stored with an event ID - const notification: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'notifications/message', - params: { level: 'info', data: 'Test notification with event ID' } - }; - - // Send the notification via transport - await transport.send(notification); - - // Read from the stream and verify we got the notification with an event ID - const reader = sseResponse.body?.getReader(); - const { value } = await reader!.read(); - const text = new TextDecoder().decode(value); - - // The response should contain an event ID - expect(text).toContain('id: '); - expect(text).toContain('"method":"notifications/message"'); - - // Extract the event ID - const idMatch = text.match(/id: ([^\n]+)/); - expect(idMatch).toBeTruthy(); - - // Verify the event was stored - const eventId = idMatch![1]; - expect(storedEvents.has(eventId)).toBe(true); - const storedEvent = storedEvents.get(eventId); - expect(eventId.startsWith('_GET_stream')).toBe(true); - expect(storedEvent?.message).toMatchObject(notification); - }); - - it('should store and replay MCP server tool notifications', async () => { - // Establish a standalone SSE stream - const sseResponse = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-session-id': sessionId - } - }); - expect(sseResponse.status).toBe(200); // Send a server notification through the MCP server - await mcpServer.server.sendLoggingMessage({ level: 'info', data: 'First notification from MCP server' }); - - // Read the notification from the SSE stream - const reader = sseResponse.body?.getReader(); - const { value } = await reader!.read(); - const text = new TextDecoder().decode(value); - - // Verify the notification was sent with an event ID - expect(text).toContain('id: '); - expect(text).toContain('First notification from MCP server'); - - // Extract the event ID - const idMatch = text.match(/id: ([^\n]+)/); - expect(idMatch).toBeTruthy(); - const firstEventId = idMatch![1]; - - // Send a second notification - await mcpServer.server.sendLoggingMessage({ level: 'info', data: 'Second notification from MCP server' }); - - // Close the first SSE stream to simulate a disconnect - await reader!.cancel(); - - // Reconnect with the Last-Event-ID to get missed messages - const reconnectResponse = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-03-26', - 'last-event-id': firstEventId - } - }); - - expect(reconnectResponse.status).toBe(200); - - // Read the replayed notification - const reconnectReader = reconnectResponse.body?.getReader(); - const reconnectData = await reconnectReader!.read(); - const reconnectText = new TextDecoder().decode(reconnectData.value); - - // Verify we received the second notification that was sent after our stored eventId - expect(reconnectText).toContain('Second notification from MCP server'); - expect(reconnectText).toContain('id: '); - }); -}); - -// Test stateless mode -describe('StreamableHTTPServerTransport in stateless mode', () => { - let server: Server; - let transport: StreamableHTTPServerTransport; - let baseUrl: URL; - - beforeEach(async () => { - const result = await createTestServer({ sessionIdGenerator: undefined }); - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - }); - - afterEach(async () => { - await stopTestServer({ server, transport }); - }); - - it('should operate without session ID validation', async () => { - // Initialize the server first - const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); - - expect(initResponse.status).toBe(200); - // Should NOT have session ID header in stateless mode - expect(initResponse.headers.get('mcp-session-id')).toBeNull(); - - // Try request without session ID - should work in stateless mode - const toolsResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.toolsList); - - expect(toolsResponse.status).toBe(200); - }); - - it('should handle POST requests with various session IDs in stateless mode', async () => { - await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); - - // Try with a random session ID - should be accepted - const response1 = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': 'random-id-1' - }, - body: JSON.stringify({ jsonrpc: '2.0', method: 'tools/list', params: {}, id: 't1' }) - }); - expect(response1.status).toBe(200); - - // Try with another random session ID - should also be accepted - const response2 = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': 'different-id-2' - }, - body: JSON.stringify({ jsonrpc: '2.0', method: 'tools/list', params: {}, id: 't2' }) - }); - expect(response2.status).toBe(200); - }); - - it('should reject second SSE stream even in stateless mode', async () => { - // Despite no session ID requirement, the transport still only allows - // one standalone SSE stream at a time - - // Initialize the server first - await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); - - // Open first SSE stream - const stream1 = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-protocol-version': '2025-03-26' - } - }); - expect(stream1.status).toBe(200); - - // Open second SSE stream - should still be rejected, stateless mode still only allows one - const stream2 = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream', - 'mcp-protocol-version': '2025-03-26' - } - }); - expect(stream2.status).toBe(409); // Conflict - only one stream allowed - }); -}); - -// Test onsessionclosed callback -describe('StreamableHTTPServerTransport onsessionclosed callback', () => { - it('should call onsessionclosed callback when session is closed via DELETE', async () => { - const mockCallback = jest.fn(); - - // Create server with onsessionclosed callback - const result = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - onsessionclosed: mockCallback - }); - - const tempServer = result.server; - const tempUrl = result.baseUrl; - - // Initialize to get a session ID - const initResponse = await sendPostRequest(tempUrl, TEST_MESSAGES.initialize); - const tempSessionId = initResponse.headers.get('mcp-session-id'); - expect(tempSessionId).toBeDefined(); - - // DELETE the session - const deleteResponse = await fetch(tempUrl, { - method: 'DELETE', - headers: { - 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(deleteResponse.status).toBe(200); - expect(mockCallback).toHaveBeenCalledWith(tempSessionId); - expect(mockCallback).toHaveBeenCalledTimes(1); - - // Clean up - tempServer.close(); - }); - - it('should not call onsessionclosed callback when not provided', async () => { - // Create server without onsessionclosed callback - const result = await createTestServer({ - sessionIdGenerator: () => randomUUID() - }); - - const tempServer = result.server; - const tempUrl = result.baseUrl; - - // Initialize to get a session ID - const initResponse = await sendPostRequest(tempUrl, TEST_MESSAGES.initialize); - const tempSessionId = initResponse.headers.get('mcp-session-id'); - - // DELETE the session - should not throw error - const deleteResponse = await fetch(tempUrl, { - method: 'DELETE', - headers: { - 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(deleteResponse.status).toBe(200); - - // Clean up - tempServer.close(); - }); - - it('should not call onsessionclosed callback for invalid session DELETE', async () => { - const mockCallback = jest.fn(); - - // Create server with onsessionclosed callback - const result = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - onsessionclosed: mockCallback - }); - - const tempServer = result.server; - const tempUrl = result.baseUrl; - - // Initialize to get a valid session - await sendPostRequest(tempUrl, TEST_MESSAGES.initialize); - - // Try to DELETE with invalid session ID - const deleteResponse = await fetch(tempUrl, { - method: 'DELETE', - headers: { - 'mcp-session-id': 'invalid-session-id', - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(deleteResponse.status).toBe(404); - expect(mockCallback).not.toHaveBeenCalled(); - - // Clean up - tempServer.close(); - }); - - it('should call onsessionclosed callback with correct session ID when multiple sessions exist', async () => { - const mockCallback = jest.fn(); - - // Create first server - const result1 = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - onsessionclosed: mockCallback - }); - - const server1 = result1.server; - const url1 = result1.baseUrl; - - // Create second server - const result2 = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - onsessionclosed: mockCallback - }); - - const server2 = result2.server; - const url2 = result2.baseUrl; - - // Initialize both servers - const initResponse1 = await sendPostRequest(url1, TEST_MESSAGES.initialize); - const sessionId1 = initResponse1.headers.get('mcp-session-id'); - - const initResponse2 = await sendPostRequest(url2, TEST_MESSAGES.initialize); - const sessionId2 = initResponse2.headers.get('mcp-session-id'); - - expect(sessionId1).toBeDefined(); - expect(sessionId2).toBeDefined(); - expect(sessionId1).not.toBe(sessionId2); - - // DELETE first session - const deleteResponse1 = await fetch(url1, { - method: 'DELETE', - headers: { - 'mcp-session-id': sessionId1 || '', - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(deleteResponse1.status).toBe(200); - expect(mockCallback).toHaveBeenCalledWith(sessionId1); - expect(mockCallback).toHaveBeenCalledTimes(1); - - // DELETE second session - const deleteResponse2 = await fetch(url2, { - method: 'DELETE', - headers: { - 'mcp-session-id': sessionId2 || '', - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(deleteResponse2.status).toBe(200); - expect(mockCallback).toHaveBeenCalledWith(sessionId2); - expect(mockCallback).toHaveBeenCalledTimes(2); - - // Clean up - server1.close(); - server2.close(); - }); -}); - -// Test async callbacks for onsessioninitialized and onsessionclosed -describe('StreamableHTTPServerTransport async callbacks', () => { - it('should support async onsessioninitialized callback', async () => { - const initializationOrder: string[] = []; - - // Create server with async onsessioninitialized callback - const result = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - onsessioninitialized: async (sessionId: string) => { - initializationOrder.push('async-start'); - // Simulate async operation - await new Promise(resolve => setTimeout(resolve, 10)); - initializationOrder.push('async-end'); - initializationOrder.push(sessionId); - } - }); - - const tempServer = result.server; - const tempUrl = result.baseUrl; - - // Initialize to trigger the callback - const initResponse = await sendPostRequest(tempUrl, TEST_MESSAGES.initialize); - const tempSessionId = initResponse.headers.get('mcp-session-id'); - - // Give time for async callback to complete - await new Promise(resolve => setTimeout(resolve, 50)); - - expect(initializationOrder).toEqual(['async-start', 'async-end', tempSessionId]); - - // Clean up - tempServer.close(); - }); - - it('should support sync onsessioninitialized callback (backwards compatibility)', async () => { - const capturedSessionId: string[] = []; - - // Create server with sync onsessioninitialized callback - const result = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - onsessioninitialized: (sessionId: string) => { - capturedSessionId.push(sessionId); - } - }); - - const tempServer = result.server; - const tempUrl = result.baseUrl; - - // Initialize to trigger the callback - const initResponse = await sendPostRequest(tempUrl, TEST_MESSAGES.initialize); - const tempSessionId = initResponse.headers.get('mcp-session-id'); - - expect(capturedSessionId).toEqual([tempSessionId]); - - // Clean up - tempServer.close(); - }); - - it('should support async onsessionclosed callback', async () => { - const closureOrder: string[] = []; - - // Create server with async onsessionclosed callback - const result = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - onsessionclosed: async (sessionId: string) => { - closureOrder.push('async-close-start'); - // Simulate async operation - await new Promise(resolve => setTimeout(resolve, 10)); - closureOrder.push('async-close-end'); - closureOrder.push(sessionId); - } - }); - - const tempServer = result.server; - const tempUrl = result.baseUrl; - - // Initialize to get a session ID - const initResponse = await sendPostRequest(tempUrl, TEST_MESSAGES.initialize); - const tempSessionId = initResponse.headers.get('mcp-session-id'); - expect(tempSessionId).toBeDefined(); - - // DELETE the session - const deleteResponse = await fetch(tempUrl, { - method: 'DELETE', - headers: { - 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(deleteResponse.status).toBe(200); - - // Give time for async callback to complete - await new Promise(resolve => setTimeout(resolve, 50)); - - expect(closureOrder).toEqual(['async-close-start', 'async-close-end', tempSessionId]); - - // Clean up - tempServer.close(); - }); - - it('should propagate errors from async onsessioninitialized callback', async () => { - const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); - - // Create server with async onsessioninitialized callback that throws - const result = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - onsessioninitialized: async (_sessionId: string) => { - throw new Error('Async initialization error'); - } - }); - - const tempServer = result.server; - const tempUrl = result.baseUrl; - - // Initialize should fail when callback throws - const initResponse = await sendPostRequest(tempUrl, TEST_MESSAGES.initialize); - expect(initResponse.status).toBe(400); - - // Clean up - consoleErrorSpy.mockRestore(); - tempServer.close(); - }); - - it('should propagate errors from async onsessionclosed callback', async () => { - const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(); - - // Create server with async onsessionclosed callback that throws - const result = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - onsessionclosed: async (_sessionId: string) => { - throw new Error('Async closure error'); - } - }); - - const tempServer = result.server; - const tempUrl = result.baseUrl; - - // Initialize to get a session ID - const initResponse = await sendPostRequest(tempUrl, TEST_MESSAGES.initialize); - const tempSessionId = initResponse.headers.get('mcp-session-id'); - - // DELETE should fail when callback throws - const deleteResponse = await fetch(tempUrl, { - method: 'DELETE', - headers: { - 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(deleteResponse.status).toBe(500); - - // Clean up - consoleErrorSpy.mockRestore(); - tempServer.close(); - }); - - it('should handle both async callbacks together', async () => { - const events: string[] = []; - - // Create server with both async callbacks - const result = await createTestServer({ - sessionIdGenerator: () => randomUUID(), - onsessioninitialized: async (sessionId: string) => { - await new Promise(resolve => setTimeout(resolve, 5)); - events.push(`initialized:${sessionId}`); - }, - onsessionclosed: async (sessionId: string) => { - await new Promise(resolve => setTimeout(resolve, 5)); - events.push(`closed:${sessionId}`); - } - }); - - const tempServer = result.server; - const tempUrl = result.baseUrl; - - // Initialize to trigger first callback - const initResponse = await sendPostRequest(tempUrl, TEST_MESSAGES.initialize); - const tempSessionId = initResponse.headers.get('mcp-session-id'); - - // Wait for async callback - await new Promise(resolve => setTimeout(resolve, 20)); - - expect(events).toContain(`initialized:${tempSessionId}`); - - // DELETE to trigger second callback - const deleteResponse = await fetch(tempUrl, { - method: 'DELETE', - headers: { - 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-03-26' - } - }); - - expect(deleteResponse.status).toBe(200); - - // Wait for async callback - await new Promise(resolve => setTimeout(resolve, 20)); - - expect(events).toContain(`closed:${tempSessionId}`); - expect(events).toHaveLength(2); - - // Clean up - tempServer.close(); - }); -}); - -// Test DNS rebinding protection -describe('StreamableHTTPServerTransport DNS rebinding protection', () => { - let server: Server; - let transport: StreamableHTTPServerTransport; - let baseUrl: URL; - - afterEach(async () => { - if (server && transport) { - await stopTestServer({ server, transport }); - } - }); - - describe('Host header validation', () => { - it('should accept requests with allowed host headers', async () => { - const result = await createTestServerWithDnsProtection({ - sessionIdGenerator: undefined, - allowedHosts: ['localhost'], - enableDnsRebindingProtection: true - }); - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - - // Note: fetch() automatically sets Host header to match the URL - // Since we're connecting to localhost:3001 and that's in allowedHosts, this should work - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream' - }, - body: JSON.stringify(TEST_MESSAGES.initialize) - }); - - expect(response.status).toBe(200); - }); - - it('should reject requests with disallowed host headers', async () => { - // Test DNS rebinding protection by creating a server that only allows example.com - // but we're connecting via localhost, so it should be rejected - const result = await createTestServerWithDnsProtection({ - sessionIdGenerator: undefined, - allowedHosts: ['example.com:3001'], - enableDnsRebindingProtection: true - }); - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream' - }, - body: JSON.stringify(TEST_MESSAGES.initialize) - }); - - expect(response.status).toBe(403); - const body = await response.json(); - expect(body.error.message).toContain('Invalid Host header:'); - }); - - it('should reject GET requests with disallowed host headers', async () => { - const result = await createTestServerWithDnsProtection({ - sessionIdGenerator: undefined, - allowedHosts: ['example.com:3001'], - enableDnsRebindingProtection: true - }); - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - - const response = await fetch(baseUrl, { - method: 'GET', - headers: { - Accept: 'text/event-stream' - } - }); - - expect(response.status).toBe(403); - }); - }); - - describe('Origin header validation', () => { - it('should accept requests with allowed origin headers', async () => { - const result = await createTestServerWithDnsProtection({ - sessionIdGenerator: undefined, - allowedOrigins: ['http://localhost:3000', 'https://example.com'], - enableDnsRebindingProtection: true - }); - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - Origin: 'http://localhost:3000' - }, - body: JSON.stringify(TEST_MESSAGES.initialize) - }); - - expect(response.status).toBe(200); - }); - - it('should reject requests with disallowed origin headers', async () => { - const result = await createTestServerWithDnsProtection({ - sessionIdGenerator: undefined, - allowedOrigins: ['http://localhost:3000'], - enableDnsRebindingProtection: true - }); - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - Origin: 'http://evil.com' - }, - body: JSON.stringify(TEST_MESSAGES.initialize) - }); - - expect(response.status).toBe(403); - const body = await response.json(); - expect(body.error.message).toBe('Invalid Origin header: http://evil.com'); - }); - }); - - describe('enableDnsRebindingProtection option', () => { - it('should skip all validations when enableDnsRebindingProtection is false', async () => { - const result = await createTestServerWithDnsProtection({ - sessionIdGenerator: undefined, - allowedHosts: ['localhost'], - allowedOrigins: ['http://localhost:3000'], - enableDnsRebindingProtection: false - }); - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - Host: 'evil.com', - Origin: 'http://evil.com' - }, - body: JSON.stringify(TEST_MESSAGES.initialize) - }); - - // Should pass even with invalid headers because protection is disabled - expect(response.status).toBe(200); - }); - }); - - describe('Combined validations', () => { - it('should validate both host and origin when both are configured', async () => { - const result = await createTestServerWithDnsProtection({ - sessionIdGenerator: undefined, - allowedHosts: ['localhost'], - allowedOrigins: ['http://localhost:3001'], - enableDnsRebindingProtection: true - }); - server = result.server; - transport = result.transport; - baseUrl = result.baseUrl; - - // Test with invalid origin (host will be automatically correct via fetch) - const response1 = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - Origin: 'http://evil.com' - }, - body: JSON.stringify(TEST_MESSAGES.initialize) - }); - - expect(response1.status).toBe(403); - const body1 = await response1.json(); - expect(body1.error.message).toBe('Invalid Origin header: http://evil.com'); - - // Test with valid origin - const response2 = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - Origin: 'http://localhost:3001' - }, - body: JSON.stringify(TEST_MESSAGES.initialize) - }); - - expect(response2.status).toBe(200); - }); - }); -}); - -/** - * Helper to create test server with DNS rebinding protection options - */ -async function createTestServerWithDnsProtection(config: { - sessionIdGenerator: (() => string) | undefined; - allowedHosts?: string[]; - allowedOrigins?: string[]; - enableDnsRebindingProtection?: boolean; -}): Promise<{ - server: Server; - transport: StreamableHTTPServerTransport; - mcpServer: McpServer; - baseUrl: URL; -}> { - const mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: { logging: {} } }); - - const port = await getFreePort(); - - if (config.allowedHosts) { - config.allowedHosts = config.allowedHosts.map(host => { - if (host.includes(':')) { - return host; - } - return `localhost:${port}`; - }); - } - - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: config.sessionIdGenerator, - allowedHosts: config.allowedHosts, - allowedOrigins: config.allowedOrigins, - enableDnsRebindingProtection: config.enableDnsRebindingProtection - }); - - await mcpServer.connect(transport); - - const httpServer = createServer(async (req, res) => { - if (req.method === 'POST') { - let body = ''; - req.on('data', chunk => (body += chunk)); - req.on('end', async () => { - const parsedBody = JSON.parse(body); - await transport.handleRequest(req as IncomingMessage & { auth?: AuthInfo }, res, parsedBody); - }); - } else { - await transport.handleRequest(req as IncomingMessage & { auth?: AuthInfo }, res); - } - }); - - await new Promise(resolve => { - httpServer.listen(port, () => resolve()); - }); - - const serverUrl = new URL(`http://localhost:${port}/`); - - return { - server: httpServer, - transport, - mcpServer, - baseUrl: serverUrl - }; -} diff --git a/typescript-sdk/src/server/streamableHttp.ts b/typescript-sdk/src/server/streamableHttp.ts deleted file mode 100644 index d57e75c..0000000 --- a/typescript-sdk/src/server/streamableHttp.ts +++ /dev/null @@ -1,807 +0,0 @@ -import { IncomingMessage, ServerResponse } from 'node:http'; -import { Transport } from '../shared/transport.js'; -import { - MessageExtraInfo, - RequestInfo, - isInitializeRequest, - isJSONRPCError, - isJSONRPCRequest, - isJSONRPCResponse, - JSONRPCMessage, - JSONRPCMessageSchema, - RequestId, - SUPPORTED_PROTOCOL_VERSIONS, - DEFAULT_NEGOTIATED_PROTOCOL_VERSION -} from '../types.js'; -import getRawBody from 'raw-body'; -import contentType from 'content-type'; -import { randomUUID } from 'node:crypto'; -import { AuthInfo } from './auth/types.js'; - -const MAXIMUM_MESSAGE_SIZE = '4mb'; - -export type StreamId = string; -export type EventId = string; - -/** - * Interface for resumability support via event storage - */ -export interface EventStore { - /** - * Stores an event for later retrieval - * @param streamId ID of the stream the event belongs to - * @param message The JSON-RPC message to store - * @returns The generated event ID for the stored event - */ - storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; - - replayEventsAfter( - lastEventId: EventId, - { - send - }: { - send: (eventId: EventId, message: JSONRPCMessage) => Promise; - } - ): Promise; -} - -/** - * Configuration options for StreamableHTTPServerTransport - */ -export interface StreamableHTTPServerTransportOptions { - /** - * Function that generates a session ID for the transport. - * The session ID SHOULD be globally unique and cryptographically secure (e.g., a securely generated UUID, a JWT, or a cryptographic hash) - * - * Return undefined to disable session management. - */ - sessionIdGenerator: (() => string) | undefined; - - /** - * A callback for session initialization events - * This is called when the server initializes a new session. - * Useful in cases when you need to register multiple mcp sessions - * and need to keep track of them. - * @param sessionId The generated session ID - */ - onsessioninitialized?: (sessionId: string) => void | Promise; - - /** - * A callback for session close events - * This is called when the server closes a session due to a DELETE request. - * Useful in cases when you need to clean up resources associated with the session. - * Note that this is different from the transport closing, if you are handling - * HTTP requests from multiple nodes you might want to close each - * StreamableHTTPServerTransport after a request is completed while still keeping the - * session open/running. - * @param sessionId The session ID that was closed - */ - onsessionclosed?: (sessionId: string) => void | Promise; - - /** - * If true, the server will return JSON responses instead of starting an SSE stream. - * This can be useful for simple request/response scenarios without streaming. - * Default is false (SSE streams are preferred). - */ - enableJsonResponse?: boolean; - - /** - * Event store for resumability support - * If provided, resumability will be enabled, allowing clients to reconnect and resume messages - */ - eventStore?: EventStore; - - /** - * List of allowed host header values for DNS rebinding protection. - * If not specified, host validation is disabled. - */ - allowedHosts?: string[]; - - /** - * List of allowed origin header values for DNS rebinding protection. - * If not specified, origin validation is disabled. - */ - allowedOrigins?: string[]; - - /** - * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). - * Default is false for backwards compatibility. - */ - enableDnsRebindingProtection?: boolean; -} - -/** - * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It supports both SSE streaming and direct HTTP responses. - * - * Usage example: - * - * ```typescript - * // Stateful mode - server sets the session ID - * const statefulTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: () => randomUUID(), - * }); - * - * // Stateless mode - explicitly set session ID to undefined - * const statelessTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: undefined, - * }); - * - * // Using with pre-parsed request body - * app.post('/mcp', (req, res) => { - * transport.handleRequest(req, res, req.body); - * }); - * ``` - * - * In stateful mode: - * - Session ID is generated and included in response headers - * - Session ID is always included in initialization responses - * - Requests with invalid session IDs are rejected with 404 Not Found - * - Non-initialization requests without a session ID are rejected with 400 Bad Request - * - State is maintained in-memory (connections, message history) - * - * In stateless mode: - * - No Session ID is included in any responses - * - No session validation is performed - */ -export class StreamableHTTPServerTransport implements Transport { - // when sessionId is not set (undefined), it means the transport is in stateless mode - private sessionIdGenerator: (() => string) | undefined; - private _started: boolean = false; - private _streamMapping: Map = new Map(); - private _requestToStreamMapping: Map = new Map(); - private _requestResponseMap: Map = new Map(); - private _initialized: boolean = false; - private _enableJsonResponse: boolean = false; - private _standaloneSseStreamId: string = '_GET_stream'; - private _eventStore?: EventStore; - private _onsessioninitialized?: (sessionId: string) => void | Promise; - private _onsessionclosed?: (sessionId: string) => void | Promise; - private _allowedHosts?: string[]; - private _allowedOrigins?: string[]; - private _enableDnsRebindingProtection: boolean; - - sessionId?: string; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; - - constructor(options: StreamableHTTPServerTransportOptions) { - this.sessionIdGenerator = options.sessionIdGenerator; - this._enableJsonResponse = options.enableJsonResponse ?? false; - this._eventStore = options.eventStore; - this._onsessioninitialized = options.onsessioninitialized; - this._onsessionclosed = options.onsessionclosed; - this._allowedHosts = options.allowedHosts; - this._allowedOrigins = options.allowedOrigins; - this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; - } - - /** - * Starts the transport. This is required by the Transport interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start(): Promise { - if (this._started) { - throw new Error('Transport already started'); - } - this._started = true; - } - - /** - * Validates request headers for DNS rebinding protection. - * @returns Error message if validation fails, undefined if validation passes. - */ - private validateRequestHeaders(req: IncomingMessage): string | undefined { - // Skip validation if protection is not enabled - if (!this._enableDnsRebindingProtection) { - return undefined; - } - - // Validate Host header if allowedHosts is configured - if (this._allowedHosts && this._allowedHosts.length > 0) { - const hostHeader = req.headers.host; - if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { - return `Invalid Host header: ${hostHeader}`; - } - } - - // Validate Origin header if allowedOrigins is configured - if (this._allowedOrigins && this._allowedOrigins.length > 0) { - const originHeader = req.headers.origin; - if (!originHeader || !this._allowedOrigins.includes(originHeader)) { - return `Invalid Origin header: ${originHeader}`; - } - } - - return undefined; - } - - /** - * Handles an incoming HTTP request, whether GET or POST - */ - async handleRequest(req: IncomingMessage & { auth?: AuthInfo }, res: ServerResponse, parsedBody?: unknown): Promise { - // Validate request headers for DNS rebinding protection - const validationError = this.validateRequestHeaders(req); - if (validationError) { - res.writeHead(403).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: validationError - }, - id: null - }) - ); - this.onerror?.(new Error(validationError)); - return; - } - - if (req.method === 'POST') { - await this.handlePostRequest(req, res, parsedBody); - } else if (req.method === 'GET') { - await this.handleGetRequest(req, res); - } else if (req.method === 'DELETE') { - await this.handleDeleteRequest(req, res); - } else { - await this.handleUnsupportedRequest(res); - } - } - - /** - * Handles GET requests for SSE stream - */ - private async handleGetRequest(req: IncomingMessage, res: ServerResponse): Promise { - // The client MUST include an Accept header, listing text/event-stream as a supported content type. - const acceptHeader = req.headers.accept; - if (!acceptHeader?.includes('text/event-stream')) { - res.writeHead(406).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Not Acceptable: Client must accept text/event-stream' - }, - id: null - }) - ); - return; - } - - // If an Mcp-Session-Id is returned by the server during initialization, - // clients using the Streamable HTTP transport MUST include it - // in the Mcp-Session-Id header on all of their subsequent HTTP requests. - if (!this.validateSession(req, res)) { - return; - } - if (!this.validateProtocolVersion(req, res)) { - return; - } - // Handle resumability: check for Last-Event-ID header - if (this._eventStore) { - const lastEventId = req.headers['last-event-id'] as string | undefined; - if (lastEventId) { - await this.replayEvents(lastEventId, res); - return; - } - } - - // The server MUST either return Content-Type: text/event-stream in response to this HTTP GET, - // or else return HTTP 405 Method Not Allowed - const headers: Record = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }; - - // After initialization, always include the session ID if we have one - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - - // Check if there's already an active standalone SSE stream for this session - if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) { - // Only one GET SSE stream is allowed per session - res.writeHead(409).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Conflict: Only one SSE stream is allowed per session' - }, - id: null - }) - ); - return; - } - - // We need to send headers immediately as messages will arrive much later, - // otherwise the client will just wait for the first message - res.writeHead(200, headers).flushHeaders(); - - // Assign the response to the standalone SSE stream - this._streamMapping.set(this._standaloneSseStreamId, res); - // Set up close handler for client disconnects - res.on('close', () => { - this._streamMapping.delete(this._standaloneSseStreamId); - }); - - // Add error handler for standalone SSE stream - res.on('error', error => { - this.onerror?.(error as Error); - }); - } - - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - private async replayEvents(lastEventId: string, res: ServerResponse): Promise { - if (!this._eventStore) { - return; - } - try { - const headers: Record = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }; - - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - res.writeHead(200, headers).flushHeaders(); - - const streamId = await this._eventStore?.replayEventsAfter(lastEventId, { - send: async (eventId: string, message: JSONRPCMessage) => { - if (!this.writeSSEEvent(res, message, eventId)) { - this.onerror?.(new Error('Failed replay events')); - res.end(); - } - } - }); - this._streamMapping.set(streamId, res); - - // Add error handler for replay stream - res.on('error', error => { - this.onerror?.(error as Error); - }); - } catch (error) { - this.onerror?.(error as Error); - } - } - - /** - * Writes an event to the SSE stream with proper formatting - */ - private writeSSEEvent(res: ServerResponse, message: JSONRPCMessage, eventId?: string): boolean { - let eventData = `event: message\n`; - // Include event ID if provided - this is important for resumability - if (eventId) { - eventData += `id: ${eventId}\n`; - } - eventData += `data: ${JSON.stringify(message)}\n\n`; - - return res.write(eventData); - } - - /** - * Handles unsupported requests (PUT, PATCH, etc.) - */ - private async handleUnsupportedRequest(res: ServerResponse): Promise { - res.writeHead(405, { - Allow: 'GET, POST, DELETE' - }).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Method not allowed.' - }, - id: null - }) - ); - } - - /** - * Handles POST requests containing JSON-RPC messages - */ - private async handlePostRequest(req: IncomingMessage & { auth?: AuthInfo }, res: ServerResponse, parsedBody?: unknown): Promise { - try { - // Validate the Accept header - const acceptHeader = req.headers.accept; - // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types. - if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) { - res.writeHead(406).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Not Acceptable: Client must accept both application/json and text/event-stream' - }, - id: null - }) - ); - return; - } - - const ct = req.headers['content-type']; - if (!ct || !ct.includes('application/json')) { - res.writeHead(415).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Unsupported Media Type: Content-Type must be application/json' - }, - id: null - }) - ); - return; - } - - const authInfo: AuthInfo | undefined = req.auth; - const requestInfo: RequestInfo = { headers: req.headers }; - - let rawMessage; - if (parsedBody !== undefined) { - rawMessage = parsedBody; - } else { - const parsedCt = contentType.parse(ct); - const body = await getRawBody(req, { - limit: MAXIMUM_MESSAGE_SIZE, - encoding: parsedCt.parameters.charset ?? 'utf-8' - }); - rawMessage = JSON.parse(body.toString()); - } - - let messages: JSONRPCMessage[]; - - // handle batch and single messages - if (Array.isArray(rawMessage)) { - messages = rawMessage.map(msg => JSONRPCMessageSchema.parse(msg)); - } else { - messages = [JSONRPCMessageSchema.parse(rawMessage)]; - } - - // Check if this is an initialization request - // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/ - const isInitializationRequest = messages.some(isInitializeRequest); - if (isInitializationRequest) { - // If it's a server with session management and the session ID is already set we should reject the request - // to avoid re-initialization. - if (this._initialized && this.sessionId !== undefined) { - res.writeHead(400).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32600, - message: 'Invalid Request: Server already initialized' - }, - id: null - }) - ); - return; - } - if (messages.length > 1) { - res.writeHead(400).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32600, - message: 'Invalid Request: Only one initialization request is allowed' - }, - id: null - }) - ); - return; - } - this.sessionId = this.sessionIdGenerator?.(); - this._initialized = true; - - // If we have a session ID and an onsessioninitialized handler, call it immediately - // This is needed in cases where the server needs to keep track of multiple sessions - if (this.sessionId && this._onsessioninitialized) { - await Promise.resolve(this._onsessioninitialized(this.sessionId)); - } - } - if (!isInitializationRequest) { - // If an Mcp-Session-Id is returned by the server during initialization, - // clients using the Streamable HTTP transport MUST include it - // in the Mcp-Session-Id header on all of their subsequent HTTP requests. - if (!this.validateSession(req, res)) { - return; - } - // Mcp-Protocol-Version header is required for all requests after initialization. - if (!this.validateProtocolVersion(req, res)) { - return; - } - } - - // check if it contains requests - const hasRequests = messages.some(isJSONRPCRequest); - - if (!hasRequests) { - // if it only contains notifications or responses, return 202 - res.writeHead(202).end(); - - // handle each message - for (const message of messages) { - this.onmessage?.(message, { authInfo, requestInfo }); - } - } else if (hasRequests) { - // The default behavior is to use SSE streaming - // but in some cases server will return JSON responses - const streamId = randomUUID(); - if (!this._enableJsonResponse) { - const headers: Record = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - Connection: 'keep-alive' - }; - - // After initialization, always include the session ID if we have one - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - - res.writeHead(200, headers); - } - // Store the response for this request to send messages back through this connection - // We need to track by request ID to maintain the connection - for (const message of messages) { - if (isJSONRPCRequest(message)) { - this._streamMapping.set(streamId, res); - this._requestToStreamMapping.set(message.id, streamId); - } - } - // Set up close handler for client disconnects - res.on('close', () => { - this._streamMapping.delete(streamId); - }); - - // Add error handler for stream write errors - res.on('error', error => { - this.onerror?.(error as Error); - }); - - // handle each message - for (const message of messages) { - this.onmessage?.(message, { authInfo, requestInfo }); - } - // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses - // This will be handled by the send() method when responses are ready - } - } catch (error) { - // return JSON-RPC formatted error - res.writeHead(400).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32700, - message: 'Parse error', - data: String(error) - }, - id: null - }) - ); - this.onerror?.(error as Error); - } - } - - /** - * Handles DELETE requests to terminate sessions - */ - private async handleDeleteRequest(req: IncomingMessage, res: ServerResponse): Promise { - if (!this.validateSession(req, res)) { - return; - } - if (!this.validateProtocolVersion(req, res)) { - return; - } - await Promise.resolve(this._onsessionclosed?.(this.sessionId!)); - await this.close(); - res.writeHead(200).end(); - } - - /** - * Validates session ID for non-initialization requests - * Returns true if the session is valid, false otherwise - */ - private validateSession(req: IncomingMessage, res: ServerResponse): boolean { - if (this.sessionIdGenerator === undefined) { - // If the sessionIdGenerator ID is not set, the session management is disabled - // and we don't need to validate the session ID - return true; - } - if (!this._initialized) { - // If the server has not been initialized yet, reject all requests - res.writeHead(400).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Server not initialized' - }, - id: null - }) - ); - return false; - } - - const sessionId = req.headers['mcp-session-id']; - - if (!sessionId) { - // Non-initialization requests without a session ID should return 400 Bad Request - res.writeHead(400).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Mcp-Session-Id header is required' - }, - id: null - }) - ); - return false; - } else if (Array.isArray(sessionId)) { - res.writeHead(400).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Mcp-Session-Id header must be a single value' - }, - id: null - }) - ); - return false; - } else if (sessionId !== this.sessionId) { - // Reject requests with invalid session ID with 404 Not Found - res.writeHead(404).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32001, - message: 'Session not found' - }, - id: null - }) - ); - return false; - } - - return true; - } - - private validateProtocolVersion(req: IncomingMessage, res: ServerResponse): boolean { - let protocolVersion = req.headers['mcp-protocol-version'] ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - if (Array.isArray(protocolVersion)) { - protocolVersion = protocolVersion[protocolVersion.length - 1]; - } - - if (!SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) { - res.writeHead(400).end( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: `Bad Request: Unsupported protocol version (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})` - }, - id: null - }) - ); - return false; - } - return true; - } - - async close(): Promise { - // Close all SSE connections - this._streamMapping.forEach(response => { - response.end(); - }); - this._streamMapping.clear(); - - // Clear any pending responses - this._requestResponseMap.clear(); - this.onclose?.(); - } - - async send(message: JSONRPCMessage, options?: { relatedRequestId?: RequestId }): Promise { - let requestId = options?.relatedRequestId; - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { - // If the message is a response, use the request ID from the message - requestId = message.id; - } - - // Check if this message should be sent on the standalone SSE stream (no request ID) - // Ignore notifications from tools (which have relatedRequestId set) - // Those will be sent via dedicated response SSE streams - if (requestId === undefined) { - // For standalone SSE streams, we can only send requests and notifications - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { - throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request'); - } - const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); - if (standaloneSse === undefined) { - // The spec says the server MAY send messages on the stream, so it's ok to discard if no stream - return; - } - - // Generate and store event ID if event store is provided - let eventId: string | undefined; - if (this._eventStore) { - // Stores the event and gets the generated event ID - eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); - } - - // Send the message to the standalone SSE stream - this.writeSSEEvent(standaloneSse, message, eventId); - return; - } - - // Get the response for this request - const streamId = this._requestToStreamMapping.get(requestId); - const response = this._streamMapping.get(streamId!); - if (!streamId) { - throw new Error(`No connection established for request ID: ${String(requestId)}`); - } - - if (!this._enableJsonResponse) { - // For SSE responses, generate event ID if event store is provided - let eventId: string | undefined; - - if (this._eventStore) { - eventId = await this._eventStore.storeEvent(streamId, message); - } - if (response) { - // Write the event to the response stream - this.writeSSEEvent(response, message, eventId); - } - } - - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { - this._requestResponseMap.set(requestId, message); - const relatedIds = Array.from(this._requestToStreamMapping.entries()) - .filter(([_, streamId]) => this._streamMapping.get(streamId) === response) - .map(([id]) => id); - - // Check if we have responses for all requests using this connection - const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id)); - - if (allResponsesReady) { - if (!response) { - throw new Error(`No connection established for request ID: ${String(requestId)}`); - } - if (this._enableJsonResponse) { - // All responses ready, send as JSON - const headers: Record = { - 'Content-Type': 'application/json' - }; - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - - const responses = relatedIds.map(id => this._requestResponseMap.get(id)!); - - response.writeHead(200, headers); - if (responses.length === 1) { - response.end(JSON.stringify(responses[0])); - } else { - response.end(JSON.stringify(responses)); - } - } else { - // End the SSE stream - response.end(); - } - // Clean up - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - } - } - } -} diff --git a/typescript-sdk/src/server/title.test.ts b/typescript-sdk/src/server/title.test.ts deleted file mode 100644 index 9606fce..0000000 --- a/typescript-sdk/src/server/title.test.ts +++ /dev/null @@ -1,217 +0,0 @@ -import { Server } from './index.js'; -import { Client } from '../client/index.js'; -import { InMemoryTransport } from '../inMemory.js'; -import { z } from 'zod'; -import { McpServer, ResourceTemplate } from './mcp.js'; - -describe('Title field backwards compatibility', () => { - it('should work with tools that have title', async () => { - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} }); - - // Register tool with title - server.registerTool( - 'test-tool', - { - title: 'Test Tool Display Name', - description: 'A test tool', - inputSchema: { - value: z.string() - } - }, - async () => ({ content: [{ type: 'text', text: 'result' }] }) - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }); - - await server.server.connect(serverTransport); - await client.connect(clientTransport); - - const tools = await client.listTools(); - expect(tools.tools).toHaveLength(1); - expect(tools.tools[0].name).toBe('test-tool'); - expect(tools.tools[0].title).toBe('Test Tool Display Name'); - expect(tools.tools[0].description).toBe('A test tool'); - }); - - it('should work with tools without title', async () => { - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} }); - - // Register tool without title - server.tool('test-tool', 'A test tool', { value: z.string() }, async () => ({ content: [{ type: 'text', text: 'result' }] })); - - const client = new Client({ name: 'test-client', version: '1.0.0' }); - - await server.server.connect(serverTransport); - await client.connect(clientTransport); - - const tools = await client.listTools(); - expect(tools.tools).toHaveLength(1); - expect(tools.tools[0].name).toBe('test-tool'); - expect(tools.tools[0].title).toBeUndefined(); - expect(tools.tools[0].description).toBe('A test tool'); - }); - - it('should work with prompts that have title using update', async () => { - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} }); - - // Register prompt with title by updating after creation - const prompt = server.prompt('test-prompt', 'A test prompt', async () => ({ - messages: [{ role: 'user', content: { type: 'text', text: 'test' } }] - })); - prompt.update({ title: 'Test Prompt Display Name' }); - - const client = new Client({ name: 'test-client', version: '1.0.0' }); - - await server.server.connect(serverTransport); - await client.connect(clientTransport); - - const prompts = await client.listPrompts(); - expect(prompts.prompts).toHaveLength(1); - expect(prompts.prompts[0].name).toBe('test-prompt'); - expect(prompts.prompts[0].title).toBe('Test Prompt Display Name'); - expect(prompts.prompts[0].description).toBe('A test prompt'); - }); - - it('should work with prompts using registerPrompt', async () => { - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} }); - - // Register prompt with title using registerPrompt - server.registerPrompt( - 'test-prompt', - { - title: 'Test Prompt Display Name', - description: 'A test prompt', - argsSchema: { input: z.string() } - }, - async ({ input }) => ({ - messages: [ - { - role: 'user', - content: { type: 'text', text: `test: ${input}` } - } - ] - }) - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }); - - await server.server.connect(serverTransport); - await client.connect(clientTransport); - - const prompts = await client.listPrompts(); - expect(prompts.prompts).toHaveLength(1); - expect(prompts.prompts[0].name).toBe('test-prompt'); - expect(prompts.prompts[0].title).toBe('Test Prompt Display Name'); - expect(prompts.prompts[0].description).toBe('A test prompt'); - expect(prompts.prompts[0].arguments).toHaveLength(1); - }); - - it('should work with resources using registerResource', async () => { - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} }); - - // Register resource with title using registerResource - server.registerResource( - 'test-resource', - 'https://example.com/test', - { - title: 'Test Resource Display Name', - description: 'A test resource', - mimeType: 'text/plain' - }, - async () => ({ - contents: [ - { - uri: 'https://example.com/test', - text: 'test content' - } - ] - }) - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }); - - await server.server.connect(serverTransport); - await client.connect(clientTransport); - - const resources = await client.listResources(); - expect(resources.resources).toHaveLength(1); - expect(resources.resources[0].name).toBe('test-resource'); - expect(resources.resources[0].title).toBe('Test Resource Display Name'); - expect(resources.resources[0].description).toBe('A test resource'); - expect(resources.resources[0].mimeType).toBe('text/plain'); - }); - - it('should work with dynamic resources using registerResource', async () => { - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} }); - - // Register dynamic resource with title using registerResource - server.registerResource( - 'user-profile', - new ResourceTemplate('users://{userId}/profile', { list: undefined }), - { - title: 'User Profile', - description: 'User profile information' - }, - async (uri, { userId }, _extra) => ({ - contents: [ - { - uri: uri.href, - text: `Profile data for user ${userId}` - } - ] - }) - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }); - - await server.server.connect(serverTransport); - await client.connect(clientTransport); - - const resourceTemplates = await client.listResourceTemplates(); - expect(resourceTemplates.resourceTemplates).toHaveLength(1); - expect(resourceTemplates.resourceTemplates[0].name).toBe('user-profile'); - expect(resourceTemplates.resourceTemplates[0].title).toBe('User Profile'); - expect(resourceTemplates.resourceTemplates[0].description).toBe('User profile information'); - expect(resourceTemplates.resourceTemplates[0].uriTemplate).toBe('users://{userId}/profile'); - - // Test reading the resource - const readResult = await client.readResource({ uri: 'users://123/profile' }); - expect(readResult.contents).toHaveLength(1); - expect(readResult.contents[0].text).toBe('Profile data for user 123'); - }); - - it('should support serverInfo with title', async () => { - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - const server = new Server( - { - name: 'test-server', - version: '1.0.0', - title: 'Test Server Display Name' - }, - { capabilities: {} } - ); - - const client = new Client({ name: 'test-client', version: '1.0.0' }); - - await server.connect(serverTransport); - await client.connect(clientTransport); - - const serverInfo = client.getServerVersion(); - expect(serverInfo?.name).toBe('test-server'); - expect(serverInfo?.version).toBe('1.0.0'); - expect(serverInfo?.title).toBe('Test Server Display Name'); - }); -}); diff --git a/typescript-sdk/src/shared/auth-utils.test.ts b/typescript-sdk/src/shared/auth-utils.test.ts deleted file mode 100644 index 04ba98d..0000000 --- a/typescript-sdk/src/shared/auth-utils.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { resourceUrlFromServerUrl, checkResourceAllowed } from './auth-utils.js'; - -describe('auth-utils', () => { - describe('resourceUrlFromServerUrl', () => { - it('should remove fragments', () => { - expect(resourceUrlFromServerUrl(new URL('https://example.com/path#fragment')).href).toBe('https://example.com/path'); - expect(resourceUrlFromServerUrl(new URL('https://example.com#fragment')).href).toBe('https://example.com/'); - expect(resourceUrlFromServerUrl(new URL('https://example.com/path?query=1#fragment')).href).toBe( - 'https://example.com/path?query=1' - ); - }); - - it('should return URL unchanged if no fragment', () => { - expect(resourceUrlFromServerUrl(new URL('https://example.com')).href).toBe('https://example.com/'); - expect(resourceUrlFromServerUrl(new URL('https://example.com/path')).href).toBe('https://example.com/path'); - expect(resourceUrlFromServerUrl(new URL('https://example.com/path?query=1')).href).toBe('https://example.com/path?query=1'); - }); - - it('should keep everything else unchanged', () => { - // Case sensitivity preserved - expect(resourceUrlFromServerUrl(new URL('https://EXAMPLE.COM/PATH')).href).toBe('https://example.com/PATH'); - // Ports preserved - expect(resourceUrlFromServerUrl(new URL('https://example.com:443/path')).href).toBe('https://example.com/path'); - expect(resourceUrlFromServerUrl(new URL('https://example.com:8080/path')).href).toBe('https://example.com:8080/path'); - // Query parameters preserved - expect(resourceUrlFromServerUrl(new URL('https://example.com?foo=bar&baz=qux')).href).toBe( - 'https://example.com/?foo=bar&baz=qux' - ); - // Trailing slashes preserved - expect(resourceUrlFromServerUrl(new URL('https://example.com/')).href).toBe('https://example.com/'); - expect(resourceUrlFromServerUrl(new URL('https://example.com/path/')).href).toBe('https://example.com/path/'); - }); - }); - - describe('resourceMatches', () => { - it('should match identical URLs', () => { - expect( - checkResourceAllowed({ requestedResource: 'https://example.com/path', configuredResource: 'https://example.com/path' }) - ).toBe(true); - expect(checkResourceAllowed({ requestedResource: 'https://example.com/', configuredResource: 'https://example.com/' })).toBe( - true - ); - }); - - it('should not match URLs with different paths', () => { - expect( - checkResourceAllowed({ requestedResource: 'https://example.com/path1', configuredResource: 'https://example.com/path2' }) - ).toBe(false); - expect( - checkResourceAllowed({ requestedResource: 'https://example.com/', configuredResource: 'https://example.com/path' }) - ).toBe(false); - }); - - it('should not match URLs with different domains', () => { - expect( - checkResourceAllowed({ requestedResource: 'https://example.com/path', configuredResource: 'https://example.org/path' }) - ).toBe(false); - }); - - it('should not match URLs with different ports', () => { - expect( - checkResourceAllowed({ requestedResource: 'https://example.com:8080/path', configuredResource: 'https://example.com/path' }) - ).toBe(false); - }); - - it('should not match URLs where one path is a sub-path of another', () => { - expect( - checkResourceAllowed({ requestedResource: 'https://example.com/mcpxxxx', configuredResource: 'https://example.com/mcp' }) - ).toBe(false); - expect( - checkResourceAllowed({ - requestedResource: 'https://example.com/folder', - configuredResource: 'https://example.com/folder/subfolder' - }) - ).toBe(false); - expect( - checkResourceAllowed({ requestedResource: 'https://example.com/api/v1', configuredResource: 'https://example.com/api' }) - ).toBe(true); - }); - - it('should handle trailing slashes vs no trailing slashes', () => { - expect( - checkResourceAllowed({ requestedResource: 'https://example.com/mcp/', configuredResource: 'https://example.com/mcp' }) - ).toBe(true); - expect( - checkResourceAllowed({ requestedResource: 'https://example.com/folder', configuredResource: 'https://example.com/folder/' }) - ).toBe(false); - }); - }); -}); diff --git a/typescript-sdk/src/shared/auth-utils.ts b/typescript-sdk/src/shared/auth-utils.ts deleted file mode 100644 index c9863da..0000000 --- a/typescript-sdk/src/shared/auth-utils.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Utilities for handling OAuth resource URIs. - */ - -/** - * Converts a server URL to a resource URL by removing the fragment. - * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". - * Keeps everything else unchanged (scheme, domain, port, path, query). - */ -export function resourceUrlFromServerUrl(url: URL | string): URL { - const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href); - resourceURL.hash = ''; // Remove fragment - return resourceURL; -} - -/** - * Checks if a requested resource URL matches a configured resource URL. - * A requested resource matches if it has the same scheme, domain, port, - * and its path starts with the configured resource's path. - * - * @param requestedResource The resource URL being requested - * @param configuredResource The resource URL that has been configured - * @returns true if the requested resource matches the configured resource, false otherwise - */ -export function checkResourceAllowed({ - requestedResource, - configuredResource -}: { - requestedResource: URL | string; - configuredResource: URL | string; -}): boolean { - const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href); - const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href); - - // Compare the origin (scheme, domain, and port) - if (requested.origin !== configured.origin) { - return false; - } - - // Handle cases like requested=/foo and configured=/foo/ - if (requested.pathname.length < configured.pathname.length) { - return false; - } - - // Check if the requested path starts with the configured path - // Ensure both paths end with / for proper comparison - // This ensures that if we have paths like "/api" and "/api/users", - // we properly detect that "/api/users" is a subpath of "/api" - // By adding a trailing slash if missing, we avoid false positives - // where paths like "/api123" would incorrectly match "/api" - const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/'; - const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/'; - - return requestedPath.startsWith(configuredPath); -} diff --git a/typescript-sdk/src/shared/auth.test.ts b/typescript-sdk/src/shared/auth.test.ts deleted file mode 100644 index 71877f3..0000000 --- a/typescript-sdk/src/shared/auth.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { describe, it, expect } from '@jest/globals'; -import { - SafeUrlSchema, - OAuthMetadataSchema, - OpenIdProviderMetadataSchema, - OAuthClientMetadataSchema, - OptionalSafeUrlSchema -} from './auth.js'; - -describe('SafeUrlSchema', () => { - it('accepts valid HTTPS URLs', () => { - expect(SafeUrlSchema.parse('https://example.com')).toBe('https://example.com'); - expect(SafeUrlSchema.parse('https://auth.example.com/oauth/authorize')).toBe('https://auth.example.com/oauth/authorize'); - }); - - it('accepts valid HTTP URLs', () => { - expect(SafeUrlSchema.parse('http://localhost:3000')).toBe('http://localhost:3000'); - }); - - it('rejects javascript: scheme URLs', () => { - expect(() => SafeUrlSchema.parse('javascript:alert(1)')).toThrow('URL cannot use javascript:, data:, or vbscript: scheme'); - expect(() => SafeUrlSchema.parse('JAVASCRIPT:alert(1)')).toThrow('URL cannot use javascript:, data:, or vbscript: scheme'); - }); - - it('rejects invalid URLs', () => { - expect(() => SafeUrlSchema.parse('not-a-url')).toThrow(); - expect(() => SafeUrlSchema.parse('')).toThrow(); - }); - - it('works with safeParse', () => { - expect(() => SafeUrlSchema.safeParse('not-a-url')).not.toThrow(); - }); -}); - -describe('OptionalSafeUrlSchema', () => { - it('accepts empty string and transforms it to undefined', () => { - expect(OptionalSafeUrlSchema.parse('')).toBe(undefined); - }); -}); - -describe('OAuthMetadataSchema', () => { - it('validates complete OAuth metadata', () => { - const metadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/oauth/authorize', - token_endpoint: 'https://auth.example.com/oauth/token', - response_types_supported: ['code'], - scopes_supported: ['read', 'write'] - }; - - expect(() => OAuthMetadataSchema.parse(metadata)).not.toThrow(); - }); - - it('rejects metadata with javascript: URLs', () => { - const metadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'javascript:alert(1)', - token_endpoint: 'https://auth.example.com/oauth/token', - response_types_supported: ['code'] - }; - - expect(() => OAuthMetadataSchema.parse(metadata)).toThrow('URL cannot use javascript:, data:, or vbscript: scheme'); - }); - - it('requires mandatory fields', () => { - const incompleteMetadata = { - issuer: 'https://auth.example.com' - }; - - expect(() => OAuthMetadataSchema.parse(incompleteMetadata)).toThrow(); - }); -}); - -describe('OpenIdProviderMetadataSchema', () => { - it('validates complete OpenID Provider metadata', () => { - const metadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/oauth/authorize', - token_endpoint: 'https://auth.example.com/oauth/token', - jwks_uri: 'https://auth.example.com/.well-known/jwks.json', - response_types_supported: ['code'], - subject_types_supported: ['public'], - id_token_signing_alg_values_supported: ['RS256'] - }; - - expect(() => OpenIdProviderMetadataSchema.parse(metadata)).not.toThrow(); - }); - - it('rejects metadata with javascript: in jwks_uri', () => { - const metadata = { - issuer: 'https://auth.example.com', - authorization_endpoint: 'https://auth.example.com/oauth/authorize', - token_endpoint: 'https://auth.example.com/oauth/token', - jwks_uri: 'javascript:alert(1)', - response_types_supported: ['code'], - subject_types_supported: ['public'], - id_token_signing_alg_values_supported: ['RS256'] - }; - - expect(() => OpenIdProviderMetadataSchema.parse(metadata)).toThrow('URL cannot use javascript:, data:, or vbscript: scheme'); - }); -}); - -describe('OAuthClientMetadataSchema', () => { - it('validates client metadata with safe URLs', () => { - const metadata = { - redirect_uris: ['https://app.example.com/callback'], - client_name: 'Test App', - client_uri: 'https://app.example.com' - }; - - expect(() => OAuthClientMetadataSchema.parse(metadata)).not.toThrow(); - }); - - it('rejects client metadata with javascript: redirect URIs', () => { - const metadata = { - redirect_uris: ['javascript:alert(1)'], - client_name: 'Test App' - }; - - expect(() => OAuthClientMetadataSchema.parse(metadata)).toThrow('URL cannot use javascript:, data:, or vbscript: scheme'); - }); -}); diff --git a/typescript-sdk/src/shared/auth.ts b/typescript-sdk/src/shared/auth.ts deleted file mode 100644 index c5ddbda..0000000 --- a/typescript-sdk/src/shared/auth.ts +++ /dev/null @@ -1,234 +0,0 @@ -import { z } from 'zod'; - -/** - * Reusable URL validation that disallows javascript: scheme - */ -export const SafeUrlSchema = z - .string() - .url() - .superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'URL must be parseable', - fatal: true - }); - - return z.NEVER; - } - }) - .refine( - url => { - const u = new URL(url); - return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; - }, - { message: 'URL cannot use javascript:, data:, or vbscript: scheme' } - ); - -/** - * RFC 9728 OAuth Protected Resource Metadata - */ -export const OAuthProtectedResourceMetadataSchema = z - .object({ - resource: z.string().url(), - authorization_servers: z.array(SafeUrlSchema).optional(), - jwks_uri: z.string().url().optional(), - scopes_supported: z.array(z.string()).optional(), - bearer_methods_supported: z.array(z.string()).optional(), - resource_signing_alg_values_supported: z.array(z.string()).optional(), - resource_name: z.string().optional(), - resource_documentation: z.string().optional(), - resource_policy_uri: z.string().url().optional(), - resource_tos_uri: z.string().url().optional(), - tls_client_certificate_bound_access_tokens: z.boolean().optional(), - authorization_details_types_supported: z.array(z.string()).optional(), - dpop_signing_alg_values_supported: z.array(z.string()).optional(), - dpop_bound_access_tokens_required: z.boolean().optional() - }) - .passthrough(); - -/** - * RFC 8414 OAuth 2.0 Authorization Server Metadata - */ -export const OAuthMetadataSchema = z - .object({ - issuer: z.string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: z.array(z.string()).optional(), - response_types_supported: z.array(z.string()), - response_modes_supported: z.array(z.string()).optional(), - grant_types_supported: z.array(z.string()).optional(), - token_endpoint_auth_methods_supported: z.array(z.string()).optional(), - token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - introspection_endpoint: z.string().optional(), - introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - code_challenge_methods_supported: z.array(z.string()).optional() - }) - .passthrough(); - -/** - * OpenID Connect Discovery 1.0 Provider Metadata - * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata - */ -export const OpenIdProviderMetadataSchema = z - .object({ - issuer: z.string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: z.array(z.string()).optional(), - response_types_supported: z.array(z.string()), - response_modes_supported: z.array(z.string()).optional(), - grant_types_supported: z.array(z.string()).optional(), - acr_values_supported: z.array(z.string()).optional(), - subject_types_supported: z.array(z.string()), - id_token_signing_alg_values_supported: z.array(z.string()), - id_token_encryption_alg_values_supported: z.array(z.string()).optional(), - id_token_encryption_enc_values_supported: z.array(z.string()).optional(), - userinfo_signing_alg_values_supported: z.array(z.string()).optional(), - userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), - userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), - request_object_signing_alg_values_supported: z.array(z.string()).optional(), - request_object_encryption_alg_values_supported: z.array(z.string()).optional(), - request_object_encryption_enc_values_supported: z.array(z.string()).optional(), - token_endpoint_auth_methods_supported: z.array(z.string()).optional(), - token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - display_values_supported: z.array(z.string()).optional(), - claim_types_supported: z.array(z.string()).optional(), - claims_supported: z.array(z.string()).optional(), - service_documentation: z.string().optional(), - claims_locales_supported: z.array(z.string()).optional(), - ui_locales_supported: z.array(z.string()).optional(), - claims_parameter_supported: z.boolean().optional(), - request_parameter_supported: z.boolean().optional(), - request_uri_parameter_supported: z.boolean().optional(), - require_request_uri_registration: z.boolean().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional() - }) - .passthrough(); - -/** - * OpenID Connect Discovery metadata that may include OAuth 2.0 fields - * This schema represents the real-world scenario where OIDC providers - * return a mix of OpenID Connect and OAuth 2.0 metadata fields - */ -export const OpenIdProviderDiscoveryMetadataSchema = OpenIdProviderMetadataSchema.merge( - OAuthMetadataSchema.pick({ - code_challenge_methods_supported: true - }) -); - -/** - * OAuth 2.1 token response - */ -export const OAuthTokensSchema = z - .object({ - access_token: z.string(), - id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect - token_type: z.string(), - expires_in: z.number().optional(), - scope: z.string().optional(), - refresh_token: z.string().optional() - }) - .strip(); - -/** - * OAuth 2.1 error response - */ -export const OAuthErrorResponseSchema = z.object({ - error: z.string(), - error_description: z.string().optional(), - error_uri: z.string().optional() -}); - -/** - * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri - */ -export const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); - -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata - */ -export const OAuthClientMetadataSchema = z - .object({ - redirect_uris: z.array(SafeUrlSchema), - token_endpoint_auth_method: z.string().optional(), - grant_types: z.array(z.string()).optional(), - response_types: z.array(z.string()).optional(), - client_name: z.string().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: z.string().optional(), - contacts: z.array(z.string()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: z.string().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: z.any().optional(), - software_id: z.string().optional(), - software_version: z.string().optional(), - software_statement: z.string().optional() - }) - .strip(); - -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration client information - */ -export const OAuthClientInformationSchema = z - .object({ - client_id: z.string(), - client_secret: z.string().optional(), - client_id_issued_at: z.number().optional(), - client_secret_expires_at: z.number().optional() - }) - .strip(); - -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) - */ -export const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); - -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration error response - */ -export const OAuthClientRegistrationErrorSchema = z - .object({ - error: z.string(), - error_description: z.string().optional() - }) - .strip(); - -/** - * RFC 7009 OAuth 2.0 Token Revocation request - */ -export const OAuthTokenRevocationRequestSchema = z - .object({ - token: z.string(), - token_type_hint: z.string().optional() - }) - .strip(); - -export type OAuthMetadata = z.infer; -export type OpenIdProviderMetadata = z.infer; -export type OpenIdProviderDiscoveryMetadata = z.infer; - -export type OAuthTokens = z.infer; -export type OAuthErrorResponse = z.infer; -export type OAuthClientMetadata = z.infer; -export type OAuthClientInformation = z.infer; -export type OAuthClientInformationFull = z.infer; -export type OAuthClientRegistrationError = z.infer; -export type OAuthTokenRevocationRequest = z.infer; -export type OAuthProtectedResourceMetadata = z.infer; - -// Unified type for authorization server metadata -export type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata; diff --git a/typescript-sdk/src/shared/metadataUtils.ts b/typescript-sdk/src/shared/metadataUtils.ts deleted file mode 100644 index d587292..0000000 --- a/typescript-sdk/src/shared/metadataUtils.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { BaseMetadata } from '../types.js'; - -/** - * Utilities for working with BaseMetadata objects. - */ - -/** - * Gets the display name for an object with BaseMetadata. - * For tools, the precedence is: title → annotations.title → name - * For other objects: title → name - * This implements the spec requirement: "if no title is provided, name should be used for display purposes" - */ -export function getDisplayName(metadata: BaseMetadata): string { - // First check for title (not undefined and not empty string) - if (metadata.title !== undefined && metadata.title !== '') { - return metadata.title; - } - - // Then check for annotations.title (only present in Tool objects) - if ('annotations' in metadata) { - const metadataWithAnnotations = metadata as BaseMetadata & { annotations?: { title?: string } }; - if (metadataWithAnnotations.annotations?.title) { - return metadataWithAnnotations.annotations.title; - } - } - - // Finally fall back to name - return metadata.name; -} diff --git a/typescript-sdk/src/shared/protocol-transport-handling.test.ts b/typescript-sdk/src/shared/protocol-transport-handling.test.ts deleted file mode 100644 index 375a0ee..0000000 --- a/typescript-sdk/src/shared/protocol-transport-handling.test.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { describe, expect, test, beforeEach } from '@jest/globals'; -import { Protocol } from './protocol.js'; -import { Transport } from './transport.js'; -import { Request, Notification, Result, JSONRPCMessage } from '../types.js'; -import { z } from 'zod'; - -// Mock Transport class -class MockTransport implements Transport { - id: string; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: unknown) => void; - sentMessages: JSONRPCMessage[] = []; - - constructor(id: string) { - this.id = id; - } - - async start(): Promise {} - - async close(): Promise { - this.onclose?.(); - } - - async send(message: JSONRPCMessage): Promise { - this.sentMessages.push(message); - } -} - -describe('Protocol transport handling bug', () => { - let protocol: Protocol; - let transportA: MockTransport; - let transportB: MockTransport; - - beforeEach(() => { - protocol = new (class extends Protocol { - protected assertCapabilityForMethod(): void {} - protected assertNotificationCapability(): void {} - protected assertRequestHandlerCapability(): void {} - })(); - - transportA = new MockTransport('A'); - transportB = new MockTransport('B'); - }); - - test('should send response to the correct transport when multiple clients are connected', async () => { - // Set up a request handler that simulates processing time - let resolveHandler: (value: Result) => void; - const handlerPromise = new Promise(resolve => { - resolveHandler = resolve; - }); - - const TestRequestSchema = z.object({ - method: z.literal('test/method'), - params: z - .object({ - from: z.string() - }) - .optional() - }); - - protocol.setRequestHandler(TestRequestSchema, async request => { - console.log(`Processing request from ${request.params?.from}`); - return handlerPromise; - }); - - // Client A connects and sends a request - await protocol.connect(transportA); - - const requestFromA = { - jsonrpc: '2.0' as const, - method: 'test/method', - params: { from: 'clientA' }, - id: 1 - }; - - // Simulate client A sending a request - transportA.onmessage?.(requestFromA); - - // While A's request is being processed, client B connects - // This overwrites the transport reference in the protocol - await protocol.connect(transportB); - - const requestFromB = { - jsonrpc: '2.0' as const, - method: 'test/method', - params: { from: 'clientB' }, - id: 2 - }; - - // Client B sends its own request - transportB.onmessage?.(requestFromB); - - // Now complete A's request - resolveHandler!({ data: 'responseForA' } as Result); - - // Wait for async operations to complete - await new Promise(resolve => setTimeout(resolve, 10)); - - // Check where the responses went - console.log('Transport A received:', transportA.sentMessages); - console.log('Transport B received:', transportB.sentMessages); - - // FIXED: Each transport now receives its own response - - // Transport A should receive response for request ID 1 - expect(transportA.sentMessages.length).toBe(1); - expect(transportA.sentMessages[0]).toMatchObject({ - jsonrpc: '2.0', - id: 1, - result: { data: 'responseForA' } - }); - - // Transport B should only receive its own response (when implemented) - expect(transportB.sentMessages.length).toBe(1); - expect(transportB.sentMessages[0]).toMatchObject({ - jsonrpc: '2.0', - id: 2, - result: { data: 'responseForA' } // Same handler result in this test - }); - }); - - test('demonstrates the timing issue with multiple rapid connections', async () => { - const delays: number[] = []; - const results: { transport: string; response: JSONRPCMessage[] }[] = []; - - const DelayedRequestSchema = z.object({ - method: z.literal('test/delayed'), - params: z - .object({ - delay: z.number(), - client: z.string() - }) - .optional() - }); - - // Set up handler with variable delay - protocol.setRequestHandler(DelayedRequestSchema, async (request, extra) => { - const delay = request.params?.delay || 0; - delays.push(delay); - - await new Promise(resolve => setTimeout(resolve, delay)); - - return { - processedBy: `handler-${extra.requestId}`, - delay: delay - } as Result; - }); - - // Rapid succession of connections and requests - await protocol.connect(transportA); - transportA.onmessage?.({ - jsonrpc: '2.0' as const, - method: 'test/delayed', - params: { delay: 50, client: 'A' }, - id: 1 - }); - - // Connect B while A is processing - setTimeout(async () => { - await protocol.connect(transportB); - transportB.onmessage?.({ - jsonrpc: '2.0' as const, - method: 'test/delayed', - params: { delay: 10, client: 'B' }, - id: 2 - }); - }, 10); - - // Wait for all processing - await new Promise(resolve => setTimeout(resolve, 100)); - - // Collect results - if (transportA.sentMessages.length > 0) { - results.push({ transport: 'A', response: transportA.sentMessages }); - } - if (transportB.sentMessages.length > 0) { - results.push({ transport: 'B', response: transportB.sentMessages }); - } - - console.log('Timing test results:', results); - - // FIXED: Each transport receives its own responses - expect(transportA.sentMessages.length).toBe(1); - expect(transportB.sentMessages.length).toBe(1); - }); -}); diff --git a/typescript-sdk/src/shared/protocol.test.ts b/typescript-sdk/src/shared/protocol.test.ts deleted file mode 100644 index 1c098ea..0000000 --- a/typescript-sdk/src/shared/protocol.test.ts +++ /dev/null @@ -1,744 +0,0 @@ -import { ZodType, z } from 'zod'; -import { ClientCapabilities, ErrorCode, McpError, Notification, Request, Result, ServerCapabilities } from '../types.js'; -import { Protocol, mergeCapabilities } from './protocol.js'; -import { Transport } from './transport.js'; - -// Mock Transport class -class MockTransport implements Transport { - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: unknown) => void; - - async start(): Promise {} - async close(): Promise { - this.onclose?.(); - } - async send(_message: unknown): Promise {} -} - -describe('protocol tests', () => { - let protocol: Protocol; - let transport: MockTransport; - let sendSpy: jest.SpyInstance; - - beforeEach(() => { - transport = new MockTransport(); - sendSpy = jest.spyOn(transport, 'send'); - protocol = new (class extends Protocol { - protected assertCapabilityForMethod(): void {} - protected assertNotificationCapability(): void {} - protected assertRequestHandlerCapability(): void {} - })(); - }); - - test('should throw a timeout error if the request exceeds the timeout', async () => { - await protocol.connect(transport); - const request = { method: 'example', params: {} }; - try { - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - await protocol.request(request, mockSchema, { - timeout: 0 - }); - } catch (error) { - expect(error).toBeInstanceOf(McpError); - if (error instanceof McpError) { - expect(error.code).toBe(ErrorCode.RequestTimeout); - } - } - }); - - test('should invoke onclose when the connection is closed', async () => { - const oncloseMock = jest.fn(); - protocol.onclose = oncloseMock; - await protocol.connect(transport); - await transport.close(); - expect(oncloseMock).toHaveBeenCalled(); - }); - - test('should not overwrite existing hooks when connecting transports', async () => { - const oncloseMock = jest.fn(); - const onerrorMock = jest.fn(); - const onmessageMock = jest.fn(); - transport.onclose = oncloseMock; - transport.onerror = onerrorMock; - transport.onmessage = onmessageMock; - await protocol.connect(transport); - transport.onclose(); - transport.onerror(new Error()); - transport.onmessage(''); - expect(oncloseMock).toHaveBeenCalled(); - expect(onerrorMock).toHaveBeenCalled(); - expect(onmessageMock).toHaveBeenCalled(); - }); - - describe('_meta preservation with onprogress', () => { - test('should preserve existing _meta when adding progressToken', async () => { - await protocol.connect(transport); - const request = { - method: 'example', - params: { - data: 'test', - _meta: { - customField: 'customValue', - anotherField: 123 - } - } - }; - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - const onProgressMock = jest.fn(); - - protocol.request(request, mockSchema, { - onprogress: onProgressMock - }); - - expect(sendSpy).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'example', - params: { - data: 'test', - _meta: { - customField: 'customValue', - anotherField: 123, - progressToken: expect.any(Number) - } - }, - jsonrpc: '2.0', - id: expect.any(Number) - }), - expect.any(Object) - ); - }); - - test('should create _meta with progressToken when no _meta exists', async () => { - await protocol.connect(transport); - const request = { - method: 'example', - params: { - data: 'test' - } - }; - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - const onProgressMock = jest.fn(); - - protocol.request(request, mockSchema, { - onprogress: onProgressMock - }); - - expect(sendSpy).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'example', - params: { - data: 'test', - _meta: { - progressToken: expect.any(Number) - } - }, - jsonrpc: '2.0', - id: expect.any(Number) - }), - expect.any(Object) - ); - }); - - test('should not modify _meta when onprogress is not provided', async () => { - await protocol.connect(transport); - const request = { - method: 'example', - params: { - data: 'test', - _meta: { - customField: 'customValue' - } - } - }; - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - - protocol.request(request, mockSchema); - - expect(sendSpy).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'example', - params: { - data: 'test', - _meta: { - customField: 'customValue' - } - }, - jsonrpc: '2.0', - id: expect.any(Number) - }), - expect.any(Object) - ); - }); - - test('should handle params being undefined with onprogress', async () => { - await protocol.connect(transport); - const request = { - method: 'example' - }; - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - const onProgressMock = jest.fn(); - - protocol.request(request, mockSchema, { - onprogress: onProgressMock - }); - - expect(sendSpy).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'example', - params: { - _meta: { - progressToken: expect.any(Number) - } - }, - jsonrpc: '2.0', - id: expect.any(Number) - }), - expect.any(Object) - ); - }); - }); - - describe('progress notification timeout behavior', () => { - beforeEach(() => { - jest.useFakeTimers(); - }); - afterEach(() => { - jest.useRealTimers(); - }); - - test('should not reset timeout when resetTimeoutOnProgress is false', async () => { - await protocol.connect(transport); - const request = { method: 'example', params: {} }; - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - const onProgressMock = jest.fn(); - const requestPromise = protocol.request(request, mockSchema, { - timeout: 1000, - resetTimeoutOnProgress: false, - onprogress: onProgressMock - }); - - jest.advanceTimersByTime(800); - - if (transport.onmessage) { - transport.onmessage({ - jsonrpc: '2.0', - method: 'notifications/progress', - params: { - progressToken: 0, - progress: 50, - total: 100 - } - }); - } - await Promise.resolve(); - - expect(onProgressMock).toHaveBeenCalledWith({ - progress: 50, - total: 100 - }); - - jest.advanceTimersByTime(201); - - await expect(requestPromise).rejects.toThrow('Request timed out'); - }); - - test('should reset timeout when progress notification is received', async () => { - await protocol.connect(transport); - const request = { method: 'example', params: {} }; - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - const onProgressMock = jest.fn(); - const requestPromise = protocol.request(request, mockSchema, { - timeout: 1000, - resetTimeoutOnProgress: true, - onprogress: onProgressMock - }); - jest.advanceTimersByTime(800); - if (transport.onmessage) { - transport.onmessage({ - jsonrpc: '2.0', - method: 'notifications/progress', - params: { - progressToken: 0, - progress: 50, - total: 100 - } - }); - } - await Promise.resolve(); - expect(onProgressMock).toHaveBeenCalledWith({ - progress: 50, - total: 100 - }); - jest.advanceTimersByTime(800); - if (transport.onmessage) { - transport.onmessage({ - jsonrpc: '2.0', - id: 0, - result: { result: 'success' } - }); - } - await Promise.resolve(); - await expect(requestPromise).resolves.toEqual({ result: 'success' }); - }); - - test('should respect maxTotalTimeout', async () => { - await protocol.connect(transport); - const request = { method: 'example', params: {} }; - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - const onProgressMock = jest.fn(); - const requestPromise = protocol.request(request, mockSchema, { - timeout: 1000, - maxTotalTimeout: 150, - resetTimeoutOnProgress: true, - onprogress: onProgressMock - }); - - // First progress notification should work - jest.advanceTimersByTime(80); - if (transport.onmessage) { - transport.onmessage({ - jsonrpc: '2.0', - method: 'notifications/progress', - params: { - progressToken: 0, - progress: 50, - total: 100 - } - }); - } - await Promise.resolve(); - expect(onProgressMock).toHaveBeenCalledWith({ - progress: 50, - total: 100 - }); - jest.advanceTimersByTime(80); - if (transport.onmessage) { - transport.onmessage({ - jsonrpc: '2.0', - method: 'notifications/progress', - params: { - progressToken: 0, - progress: 75, - total: 100 - } - }); - } - await expect(requestPromise).rejects.toThrow('Maximum total timeout exceeded'); - expect(onProgressMock).toHaveBeenCalledTimes(1); - }); - - test('should timeout if no progress received within timeout period', async () => { - await protocol.connect(transport); - const request = { method: 'example', params: {} }; - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - const requestPromise = protocol.request(request, mockSchema, { - timeout: 100, - resetTimeoutOnProgress: true - }); - jest.advanceTimersByTime(101); - await expect(requestPromise).rejects.toThrow('Request timed out'); - }); - - test('should handle multiple progress notifications correctly', async () => { - await protocol.connect(transport); - const request = { method: 'example', params: {} }; - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - const onProgressMock = jest.fn(); - const requestPromise = protocol.request(request, mockSchema, { - timeout: 1000, - resetTimeoutOnProgress: true, - onprogress: onProgressMock - }); - - // Simulate multiple progress updates - for (let i = 1; i <= 3; i++) { - jest.advanceTimersByTime(800); - if (transport.onmessage) { - transport.onmessage({ - jsonrpc: '2.0', - method: 'notifications/progress', - params: { - progressToken: 0, - progress: i * 25, - total: 100 - } - }); - } - await Promise.resolve(); - expect(onProgressMock).toHaveBeenNthCalledWith(i, { - progress: i * 25, - total: 100 - }); - } - if (transport.onmessage) { - transport.onmessage({ - jsonrpc: '2.0', - id: 0, - result: { result: 'success' } - }); - } - await Promise.resolve(); - await expect(requestPromise).resolves.toEqual({ result: 'success' }); - }); - - test('should handle progress notifications with message field', async () => { - await protocol.connect(transport); - const request = { method: 'example', params: {} }; - const mockSchema: ZodType<{ result: string }> = z.object({ - result: z.string() - }); - const onProgressMock = jest.fn(); - - const requestPromise = protocol.request(request, mockSchema, { - timeout: 1000, - onprogress: onProgressMock - }); - - jest.advanceTimersByTime(200); - - if (transport.onmessage) { - transport.onmessage({ - jsonrpc: '2.0', - method: 'notifications/progress', - params: { - progressToken: 0, - progress: 25, - total: 100, - message: 'Initializing process...' - } - }); - } - await Promise.resolve(); - - expect(onProgressMock).toHaveBeenCalledWith({ - progress: 25, - total: 100, - message: 'Initializing process...' - }); - - jest.advanceTimersByTime(200); - - if (transport.onmessage) { - transport.onmessage({ - jsonrpc: '2.0', - method: 'notifications/progress', - params: { - progressToken: 0, - progress: 75, - total: 100, - message: 'Processing data...' - } - }); - } - await Promise.resolve(); - - expect(onProgressMock).toHaveBeenCalledWith({ - progress: 75, - total: 100, - message: 'Processing data...' - }); - - if (transport.onmessage) { - transport.onmessage({ - jsonrpc: '2.0', - id: 0, - result: { result: 'success' } - }); - } - await Promise.resolve(); - await expect(requestPromise).resolves.toEqual({ result: 'success' }); - }); - }); - - describe('Debounced Notifications', () => { - // We need to flush the microtask queue to test the debouncing logic. - // This helper function does that. - const flushMicrotasks = () => new Promise(resolve => setImmediate(resolve)); - - it('should NOT debounce a notification that has parameters', async () => { - // ARRANGE - protocol = new (class extends Protocol { - protected assertCapabilityForMethod(): void {} - protected assertNotificationCapability(): void {} - protected assertRequestHandlerCapability(): void {} - })({ debouncedNotificationMethods: ['test/debounced_with_params'] }); - await protocol.connect(transport); - - // ACT - // These notifications are configured for debouncing but contain params, so they should be sent immediately. - await protocol.notification({ method: 'test/debounced_with_params', params: { data: 1 } }); - await protocol.notification({ method: 'test/debounced_with_params', params: { data: 2 } }); - - // ASSERT - // Both should have been sent immediately to avoid data loss. - expect(sendSpy).toHaveBeenCalledTimes(2); - expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ params: { data: 1 } }), undefined); - expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ params: { data: 2 } }), undefined); - }); - - it('should NOT debounce a notification that has a relatedRequestId', async () => { - // ARRANGE - protocol = new (class extends Protocol { - protected assertCapabilityForMethod(): void {} - protected assertNotificationCapability(): void {} - protected assertRequestHandlerCapability(): void {} - })({ debouncedNotificationMethods: ['test/debounced_with_options'] }); - await protocol.connect(transport); - - // ACT - await protocol.notification({ method: 'test/debounced_with_options' }, { relatedRequestId: 'req-1' }); - await protocol.notification({ method: 'test/debounced_with_options' }, { relatedRequestId: 'req-2' }); - - // ASSERT - expect(sendSpy).toHaveBeenCalledTimes(2); - expect(sendSpy).toHaveBeenCalledWith(expect.any(Object), { relatedRequestId: 'req-1' }); - expect(sendSpy).toHaveBeenCalledWith(expect.any(Object), { relatedRequestId: 'req-2' }); - }); - - it('should clear pending debounced notifications on connection close', async () => { - // ARRANGE - protocol = new (class extends Protocol { - protected assertCapabilityForMethod(): void {} - protected assertNotificationCapability(): void {} - protected assertRequestHandlerCapability(): void {} - })({ debouncedNotificationMethods: ['test/debounced'] }); - await protocol.connect(transport); - - // ACT - // Schedule a notification but don't flush the microtask queue. - protocol.notification({ method: 'test/debounced' }); - - // Close the connection. This should clear the pending set. - await protocol.close(); - - // Now, flush the microtask queue. - await flushMicrotasks(); - - // ASSERT - // The send should never have happened because the transport was cleared. - expect(sendSpy).not.toHaveBeenCalled(); - }); - - it('should debounce multiple synchronous calls when params property is omitted', async () => { - // ARRANGE - protocol = new (class extends Protocol { - protected assertCapabilityForMethod(): void {} - protected assertNotificationCapability(): void {} - protected assertRequestHandlerCapability(): void {} - })({ debouncedNotificationMethods: ['test/debounced'] }); - await protocol.connect(transport); - - // ACT - // This is the more idiomatic way to write a notification with no params. - protocol.notification({ method: 'test/debounced' }); - protocol.notification({ method: 'test/debounced' }); - protocol.notification({ method: 'test/debounced' }); - - expect(sendSpy).not.toHaveBeenCalled(); - await flushMicrotasks(); - - // ASSERT - expect(sendSpy).toHaveBeenCalledTimes(1); - // The final sent object might not even have the `params` key, which is fine. - // We can check that it was called and that the params are "falsy". - const sentNotification = sendSpy.mock.calls[0][0]; - expect(sentNotification.method).toBe('test/debounced'); - expect(sentNotification.params).toBeUndefined(); - }); - - it('should debounce calls when params is explicitly undefined', async () => { - // ARRANGE - protocol = new (class extends Protocol { - protected assertCapabilityForMethod(): void {} - protected assertNotificationCapability(): void {} - protected assertRequestHandlerCapability(): void {} - })({ debouncedNotificationMethods: ['test/debounced'] }); - await protocol.connect(transport); - - // ACT - protocol.notification({ method: 'test/debounced', params: undefined }); - protocol.notification({ method: 'test/debounced', params: undefined }); - await flushMicrotasks(); - - // ASSERT - expect(sendSpy).toHaveBeenCalledTimes(1); - expect(sendSpy).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'test/debounced', - params: undefined - }), - undefined - ); - }); - - it('should send non-debounced notifications immediately and multiple times', async () => { - // ARRANGE - protocol = new (class extends Protocol { - protected assertCapabilityForMethod(): void {} - protected assertNotificationCapability(): void {} - protected assertRequestHandlerCapability(): void {} - })({ debouncedNotificationMethods: ['test/debounced'] }); // Configure for a different method - await protocol.connect(transport); - - // ACT - // Call a non-debounced notification method multiple times. - await protocol.notification({ method: 'test/immediate' }); - await protocol.notification({ method: 'test/immediate' }); - - // ASSERT - // Since this method is not in the debounce list, it should be sent every time. - expect(sendSpy).toHaveBeenCalledTimes(2); - }); - - it('should not debounce any notifications if the option is not provided', async () => { - // ARRANGE - // Use the default protocol from beforeEach, which has no debounce options. - await protocol.connect(transport); - - // ACT - await protocol.notification({ method: 'any/method' }); - await protocol.notification({ method: 'any/method' }); - - // ASSERT - // Without the config, behavior should be immediate sending. - expect(sendSpy).toHaveBeenCalledTimes(2); - }); - - it('should handle sequential batches of debounced notifications correctly', async () => { - // ARRANGE - protocol = new (class extends Protocol { - protected assertCapabilityForMethod(): void {} - protected assertNotificationCapability(): void {} - protected assertRequestHandlerCapability(): void {} - })({ debouncedNotificationMethods: ['test/debounced'] }); - await protocol.connect(transport); - - // ACT (Batch 1) - protocol.notification({ method: 'test/debounced' }); - protocol.notification({ method: 'test/debounced' }); - await flushMicrotasks(); - - // ASSERT (Batch 1) - expect(sendSpy).toHaveBeenCalledTimes(1); - - // ACT (Batch 2) - // After the first batch has been sent, a new batch should be possible. - protocol.notification({ method: 'test/debounced' }); - protocol.notification({ method: 'test/debounced' }); - await flushMicrotasks(); - - // ASSERT (Batch 2) - // The total number of sends should now be 2. - expect(sendSpy).toHaveBeenCalledTimes(2); - }); - }); -}); - -describe('mergeCapabilities', () => { - it('should merge client capabilities', () => { - const base: ClientCapabilities = { - sampling: {}, - roots: { - listChanged: true - } - }; - - const additional: ClientCapabilities = { - experimental: { - feature: true - }, - elicitation: {}, - roots: { - newProp: true - } - }; - - const merged = mergeCapabilities(base, additional); - expect(merged).toEqual({ - sampling: {}, - elicitation: {}, - roots: { - listChanged: true, - newProp: true - }, - experimental: { - feature: true - } - }); - }); - - it('should merge server capabilities', () => { - const base: ServerCapabilities = { - logging: {}, - prompts: { - listChanged: true - } - }; - - const additional: ServerCapabilities = { - resources: { - subscribe: true - }, - prompts: { - newProp: true - } - }; - - const merged = mergeCapabilities(base, additional); - expect(merged).toEqual({ - logging: {}, - prompts: { - listChanged: true, - newProp: true - }, - resources: { - subscribe: true - } - }); - }); - - it('should override existing values with additional values', () => { - const base: ServerCapabilities = { - prompts: { - listChanged: false - } - }; - - const additional: ServerCapabilities = { - prompts: { - listChanged: true - } - }; - - const merged = mergeCapabilities(base, additional); - expect(merged.prompts!.listChanged).toBe(true); - }); - - it('should handle empty objects', () => { - const base = {}; - const additional = {}; - const merged = mergeCapabilities(base, additional); - expect(merged).toEqual({}); - }); -}); diff --git a/typescript-sdk/src/shared/protocol.ts b/typescript-sdk/src/shared/protocol.ts deleted file mode 100644 index 5cb9694..0000000 --- a/typescript-sdk/src/shared/protocol.ts +++ /dev/null @@ -1,708 +0,0 @@ -import { ZodLiteral, ZodObject, ZodType, z } from 'zod'; -import { - CancelledNotificationSchema, - ClientCapabilities, - ErrorCode, - isJSONRPCError, - isJSONRPCRequest, - isJSONRPCResponse, - isJSONRPCNotification, - JSONRPCError, - JSONRPCNotification, - JSONRPCRequest, - JSONRPCResponse, - McpError, - Notification, - PingRequestSchema, - Progress, - ProgressNotification, - ProgressNotificationSchema, - Request, - RequestId, - Result, - ServerCapabilities, - RequestMeta, - MessageExtraInfo, - RequestInfo -} from '../types.js'; -import { Transport, TransportSendOptions } from './transport.js'; -import { AuthInfo } from '../server/auth/types.js'; - -/** - * Callback for progress notifications. - */ -export type ProgressCallback = (progress: Progress) => void; - -/** - * Additional initialization options. - */ -export type ProtocolOptions = { - /** - * Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities. - * - * Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those. - * - * Currently this defaults to false, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to true. - */ - enforceStrictCapabilities?: boolean; - /** - * An array of notification method names that should be automatically debounced. - * Any notifications with a method in this list will be coalesced if they - * occur in the same tick of the event loop. - * e.g., ['notifications/tools/list_changed'] - */ - debouncedNotificationMethods?: string[]; -}; - -/** - * The default request timeout, in miliseconds. - */ -export const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; - -/** - * Options that can be given per request. - */ -export type RequestOptions = { - /** - * If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked. - */ - onprogress?: ProgressCallback; - - /** - * Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request(). - */ - signal?: AbortSignal; - - /** - * A timeout (in milliseconds) for this request. If exceeded, an McpError with code `RequestTimeout` will be raised from request(). - * - * If not specified, `DEFAULT_REQUEST_TIMEOUT_MSEC` will be used as the timeout. - */ - timeout?: number; - - /** - * If true, receiving a progress notification will reset the request timeout. - * This is useful for long-running operations that send periodic progress updates. - * Default: false - */ - resetTimeoutOnProgress?: boolean; - - /** - * Maximum total time (in milliseconds) to wait for a response. - * If exceeded, an McpError with code `RequestTimeout` will be raised, regardless of progress notifications. - * If not specified, there is no maximum total timeout. - */ - maxTotalTimeout?: number; -} & TransportSendOptions; - -/** - * Options that can be given per notification. - */ -export type NotificationOptions = { - /** - * May be used to indicate to the transport which incoming request to associate this outgoing notification with. - */ - relatedRequestId?: RequestId; -}; - -/** - * Extra data given to request handlers. - */ -export type RequestHandlerExtra = { - /** - * An abort signal used to communicate if the request was cancelled from the sender's side. - */ - signal: AbortSignal; - - /** - * Information about a validated access token, provided to request handlers. - */ - authInfo?: AuthInfo; - - /** - * The session ID from the transport, if available. - */ - sessionId?: string; - - /** - * Metadata from the original request. - */ - _meta?: RequestMeta; - - /** - * The JSON-RPC ID of the request being handled. - * This can be useful for tracking or logging purposes. - */ - requestId: RequestId; - - /** - * The original HTTP request. - */ - requestInfo?: RequestInfo; - - /** - * Sends a notification that relates to the current request being handled. - * - * This is used by certain transports to correctly associate related messages. - */ - sendNotification: (notification: SendNotificationT) => Promise; - - /** - * Sends a request that relates to the current request being handled. - * - * This is used by certain transports to correctly associate related messages. - */ - sendRequest: >(request: SendRequestT, resultSchema: U, options?: RequestOptions) => Promise>; -}; - -/** - * Information about a request's timeout state - */ -type TimeoutInfo = { - timeoutId: ReturnType; - startTime: number; - timeout: number; - maxTotalTimeout?: number; - resetTimeoutOnProgress: boolean; - onTimeout: () => void; -}; - -/** - * Implements MCP protocol framing on top of a pluggable transport, including - * features like request/response linking, notifications, and progress. - */ -export abstract class Protocol { - private _transport?: Transport; - private _requestMessageId = 0; - private _requestHandlers: Map< - string, - (request: JSONRPCRequest, extra: RequestHandlerExtra) => Promise - > = new Map(); - private _requestHandlerAbortControllers: Map = new Map(); - private _notificationHandlers: Map Promise> = new Map(); - private _responseHandlers: Map void> = new Map(); - private _progressHandlers: Map = new Map(); - private _timeoutInfo: Map = new Map(); - private _pendingDebouncedNotifications = new Set(); - - /** - * Callback for when the connection is closed for any reason. - * - * This is invoked when close() is called as well. - */ - onclose?: () => void; - - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror?: (error: Error) => void; - - /** - * A handler to invoke for any request types that do not have their own handler installed. - */ - fallbackRequestHandler?: (request: JSONRPCRequest, extra: RequestHandlerExtra) => Promise; - - /** - * A handler to invoke for any notification types that do not have their own handler installed. - */ - fallbackNotificationHandler?: (notification: Notification) => Promise; - - constructor(private _options?: ProtocolOptions) { - this.setNotificationHandler(CancelledNotificationSchema, notification => { - const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); - controller?.abort(notification.params.reason); - }); - - this.setNotificationHandler(ProgressNotificationSchema, notification => { - this._onprogress(notification as unknown as ProgressNotification); - }); - - this.setRequestHandler( - PingRequestSchema, - // Automatic pong by default. - _request => ({}) as SendResultT - ); - } - - private _setupTimeout( - messageId: number, - timeout: number, - maxTotalTimeout: number | undefined, - onTimeout: () => void, - resetTimeoutOnProgress: boolean = false - ) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - - private _resetTimeout(messageId: number): boolean { - const info = this._timeoutInfo.get(messageId); - if (!info) return false; - - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw new McpError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - - private _cleanupTimeout(messageId: number) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - async connect(transport: Transport): Promise { - this._transport = transport; - const _onclose = this.transport?.onclose; - this._transport.onclose = () => { - _onclose?.(); - this._onclose(); - }; - - const _onerror = this.transport?.onerror; - this._transport.onerror = (error: Error) => { - _onerror?.(error); - this._onerror(error); - }; - - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage?.(message, extra); - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { - this._onresponse(message); - } else if (isJSONRPCRequest(message)) { - this._onrequest(message, extra); - } else if (isJSONRPCNotification(message)) { - this._onnotification(message); - } else { - this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); - } - }; - - await this._transport.start(); - } - - private _onclose(): void { - const responseHandlers = this._responseHandlers; - this._responseHandlers = new Map(); - this._progressHandlers.clear(); - this._pendingDebouncedNotifications.clear(); - this._transport = undefined; - this.onclose?.(); - - const error = new McpError(ErrorCode.ConnectionClosed, 'Connection closed'); - for (const handler of responseHandlers.values()) { - handler(error); - } - } - - private _onerror(error: Error): void { - this.onerror?.(error); - } - - private _onnotification(notification: JSONRPCNotification): void { - const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; - - // Ignore notifications not being subscribed to. - if (handler === undefined) { - return; - } - - // Starting with Promise.resolve() puts any synchronous errors into the monad as well. - Promise.resolve() - .then(() => handler(notification)) - .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); - } - - private _onrequest(request: JSONRPCRequest, extra?: MessageExtraInfo): void { - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - - // Capture the current transport at request time to ensure responses go to the correct client - const capturedTransport = this._transport; - - if (handler === undefined) { - capturedTransport - ?.send({ - jsonrpc: '2.0', - id: request.id, - error: { - code: ErrorCode.MethodNotFound, - message: 'Method not found' - } - }) - .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); - return; - } - - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - - const fullExtra: RequestHandlerExtra = { - signal: abortController.signal, - sessionId: capturedTransport?.sessionId, - _meta: request.params?._meta, - sendNotification: notification => this.notification(notification, { relatedRequestId: request.id }), - sendRequest: (r, resultSchema, options?) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }), - authInfo: extra?.authInfo, - requestId: request.id, - requestInfo: extra?.requestInfo - }; - - // Starting with Promise.resolve() puts any synchronous errors into the monad as well. - Promise.resolve() - .then(() => handler(request, fullExtra)) - .then( - result => { - if (abortController.signal.aborted) { - return; - } - - return capturedTransport?.send({ - result, - jsonrpc: '2.0', - id: request.id - }); - }, - error => { - if (abortController.signal.aborted) { - return; - } - - return capturedTransport?.send({ - jsonrpc: '2.0', - id: request.id, - error: { - code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError, - message: error.message ?? 'Internal error' - } - }); - } - ) - .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) - .finally(() => { - this._requestHandlerAbortControllers.delete(request.id); - }); - } - - private _onprogress(notification: ProgressNotification): void { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { - try { - this._resetTimeout(messageId); - } catch (error) { - responseHandler(error as Error); - return; - } - } - - handler(params); - } - - private _onresponse(response: JSONRPCResponse | JSONRPCError): void { - const messageId = Number(response.id); - const handler = this._responseHandlers.get(messageId); - if (handler === undefined) { - this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - - if (isJSONRPCResponse(response)) { - handler(response); - } else { - const error = new McpError(response.error.code, response.error.message, response.error.data); - handler(error); - } - } - - get transport(): Transport | undefined { - return this._transport; - } - - /** - * Closes the connection. - */ - async close(): Promise { - await this._transport?.close(); - } - - /** - * A method to check if a capability is supported by the remote side, for the given method to be called. - * - * This should be implemented by subclasses. - */ - protected abstract assertCapabilityForMethod(method: SendRequestT['method']): void; - - /** - * A method to check if a notification is supported by the local side, for the given method to be sent. - * - * This should be implemented by subclasses. - */ - protected abstract assertNotificationCapability(method: SendNotificationT['method']): void; - - /** - * A method to check if a request handler is supported by the local side, for the given method to be handled. - * - * This should be implemented by subclasses. - */ - protected abstract assertRequestHandlerCapability(method: string): void; - - /** - * Sends a request and wait for a response. - * - * Do not use this method to emit notifications! Use notification() instead. - */ - request>(request: SendRequestT, resultSchema: T, options?: RequestOptions): Promise> { - const { relatedRequestId, resumptionToken, onresumptiontoken } = options ?? {}; - - return new Promise((resolve, reject) => { - if (!this._transport) { - reject(new Error('Not connected')); - return; - } - - if (this._options?.enforceStrictCapabilities === true) { - this.assertCapabilityForMethod(request.method); - } - - options?.signal?.throwIfAborted(); - - const messageId = this._requestMessageId++; - const jsonrpcRequest: JSONRPCRequest = { - ...request, - jsonrpc: '2.0', - id: messageId - }; - - if (options?.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...(request.params?._meta || {}), - progressToken: messageId - } - }; - } - - const cancel = (reason: unknown) => { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - - this._transport - ?.send( - { - jsonrpc: '2.0', - method: 'notifications/cancelled', - params: { - requestId: messageId, - reason: String(reason) - } - }, - { relatedRequestId, resumptionToken, onresumptiontoken } - ) - .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); - - reject(reason); - }; - - this._responseHandlers.set(messageId, response => { - if (options?.signal?.aborted) { - return; - } - - if (response instanceof Error) { - return reject(response); - } - - try { - const result = resultSchema.parse(response.result); - resolve(result); - } catch (error) { - reject(error); - } - }); - - options?.signal?.addEventListener('abort', () => { - cancel(options?.signal?.reason); - }); - - const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(new McpError(ErrorCode.RequestTimeout, 'Request timed out', { timeout })); - - this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); - - this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { - this._cleanupTimeout(messageId); - reject(error); - }); - }); - } - - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification: SendNotificationT, options?: NotificationOptions): Promise { - if (!this._transport) { - throw new Error('Not connected'); - } - - this.assertNotificationCapability(notification.method); - - const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; - // A notification can only be debounced if it's in the list AND it's "simple" - // (i.e., has no parameters and no related request ID that could be lost). - const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId; - - if (canDebounce) { - // If a notification of this type is already scheduled, do nothing. - if (this._pendingDebouncedNotifications.has(notification.method)) { - return; - } - - // Mark this notification type as pending. - this._pendingDebouncedNotifications.add(notification.method); - - // Schedule the actual send to happen in the next microtask. - // This allows all synchronous calls in the current event loop tick to be coalesced. - Promise.resolve().then(() => { - // Un-mark the notification so the next one can be scheduled. - this._pendingDebouncedNotifications.delete(notification.method); - - // SAFETY CHECK: If the connection was closed while this was pending, abort. - if (!this._transport) { - return; - } - - const jsonrpcNotification: JSONRPCNotification = { - ...notification, - jsonrpc: '2.0' - }; - // Send the notification, but don't await it here to avoid blocking. - // Handle potential errors with a .catch(). - this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error)); - }); - - // Return immediately. - return; - } - - const jsonrpcNotification: JSONRPCNotification = { - ...notification, - jsonrpc: '2.0' - }; - - await this._transport.send(jsonrpcNotification, options); - } - - /** - * Registers a handler to invoke when this protocol object receives a request with the given method. - * - * Note that this will replace any previous request handler for the same method. - */ - setRequestHandler< - T extends ZodObject<{ - method: ZodLiteral; - }> - >( - requestSchema: T, - handler: (request: z.infer, extra: RequestHandlerExtra) => SendResultT | Promise - ): void { - const method = requestSchema.shape.method.value; - this.assertRequestHandlerCapability(method); - - this._requestHandlers.set(method, (request, extra) => { - return Promise.resolve(handler(requestSchema.parse(request), extra)); - }); - } - - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method: string): void { - this._requestHandlers.delete(method); - } - - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method: string): void { - if (this._requestHandlers.has(method)) { - throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - } - - /** - * Registers a handler to invoke when this protocol object receives a notification with the given method. - * - * Note that this will replace any previous notification handler for the same method. - */ - setNotificationHandler< - T extends ZodObject<{ - method: ZodLiteral; - }> - >(notificationSchema: T, handler: (notification: z.infer) => void | Promise): void { - this._notificationHandlers.set(notificationSchema.shape.method.value, notification => - Promise.resolve(handler(notificationSchema.parse(notification))) - ); - } - - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method: string): void { - this._notificationHandlers.delete(method); - } -} - -export function mergeCapabilities(base: T, additional: T): T { - return Object.entries(additional).reduce( - (acc, [key, value]) => { - if (value && typeof value === 'object') { - acc[key] = acc[key] ? { ...acc[key], ...value } : value; - } else { - acc[key] = value; - } - return acc; - }, - { ...base } - ); -} diff --git a/typescript-sdk/src/shared/stdio.test.ts b/typescript-sdk/src/shared/stdio.test.ts deleted file mode 100644 index e41c938..0000000 --- a/typescript-sdk/src/shared/stdio.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { JSONRPCMessage } from '../types.js'; -import { ReadBuffer } from './stdio.js'; - -const testMessage: JSONRPCMessage = { - jsonrpc: '2.0', - method: 'foobar' -}; - -test('should have no messages after initialization', () => { - const readBuffer = new ReadBuffer(); - expect(readBuffer.readMessage()).toBeNull(); -}); - -test('should only yield a message after a newline', () => { - const readBuffer = new ReadBuffer(); - - readBuffer.append(Buffer.from(JSON.stringify(testMessage))); - expect(readBuffer.readMessage()).toBeNull(); - - readBuffer.append(Buffer.from('\n')); - expect(readBuffer.readMessage()).toEqual(testMessage); - expect(readBuffer.readMessage()).toBeNull(); -}); - -test('should be reusable after clearing', () => { - const readBuffer = new ReadBuffer(); - - readBuffer.append(Buffer.from('foobar')); - readBuffer.clear(); - expect(readBuffer.readMessage()).toBeNull(); - - readBuffer.append(Buffer.from(JSON.stringify(testMessage))); - readBuffer.append(Buffer.from('\n')); - expect(readBuffer.readMessage()).toEqual(testMessage); -}); diff --git a/typescript-sdk/src/shared/stdio.ts b/typescript-sdk/src/shared/stdio.ts deleted file mode 100644 index fe14612..0000000 --- a/typescript-sdk/src/shared/stdio.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { JSONRPCMessage, JSONRPCMessageSchema } from '../types.js'; - -/** - * Buffers a continuous stdio stream into discrete JSON-RPC messages. - */ -export class ReadBuffer { - private _buffer?: Buffer; - - append(chunk: Buffer): void { - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - - readMessage(): JSONRPCMessage | null { - if (!this._buffer) { - return null; - } - - const index = this._buffer.indexOf('\n'); - if (index === -1) { - return null; - } - - const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, ''); - this._buffer = this._buffer.subarray(index + 1); - return deserializeMessage(line); - } - - clear(): void { - this._buffer = undefined; - } -} - -export function deserializeMessage(line: string): JSONRPCMessage { - return JSONRPCMessageSchema.parse(JSON.parse(line)); -} - -export function serializeMessage(message: JSONRPCMessage): string { - return JSON.stringify(message) + '\n'; -} diff --git a/typescript-sdk/src/shared/transport.ts b/typescript-sdk/src/shared/transport.ts deleted file mode 100644 index c64f622..0000000 --- a/typescript-sdk/src/shared/transport.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types.js'; - -export type FetchLike = (url: string | URL, init?: RequestInit) => Promise; - -/** - * Options for sending a JSON-RPC message. - */ -export type TransportSendOptions = { - /** - * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. - */ - relatedRequestId?: RequestId; - - /** - * The resumption token used to continue long-running requests that were interrupted. - * - * This allows clients to reconnect and continue from where they left off, if supported by the transport. - */ - resumptionToken?: string; - - /** - * A callback that is invoked when the resumption token changes, if supported by the transport. - * - * This allows clients to persist the latest token for potential reconnection. - */ - onresumptiontoken?: (token: string) => void; -}; -/** - * Describes the minimal contract for a MCP transport that a client or server can communicate over. - */ -export interface Transport { - /** - * Starts processing messages on the transport, including any connection steps that might need to be taken. - * - * This method should only be called after callbacks are installed, or else messages may be lost. - * - * NOTE: This method should not be called explicitly when using Client, Server, or Protocol classes, as they will implicitly call start(). - */ - start(): Promise; - - /** - * Sends a JSON-RPC message (request or response). - * - * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. - */ - send(message: JSONRPCMessage, options?: TransportSendOptions): Promise; - - /** - * Closes the connection. - */ - close(): Promise; - - /** - * Callback for when the connection is closed for any reason. - * - * This should be invoked when close() is called as well. - */ - onclose?: () => void; - - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror?: (error: Error) => void; - - /** - * Callback for when a message (request or response) is received over the connection. - * - * Includes the requestInfo and authInfo if the transport is authenticated. - * - * The requestInfo can be used to get the original request information (headers, etc.) - */ - onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; - - /** - * The session ID generated for this connection. - */ - sessionId?: string; - - /** - * Sets the protocol version used for the connection (called when the initialize response is received). - */ - setProtocolVersion?: (version: string) => void; -} diff --git a/typescript-sdk/src/shared/uriTemplate.test.ts b/typescript-sdk/src/shared/uriTemplate.test.ts deleted file mode 100644 index 043f932..0000000 --- a/typescript-sdk/src/shared/uriTemplate.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { UriTemplate } from './uriTemplate.js'; - -describe('UriTemplate', () => { - describe('isTemplate', () => { - it('should return true for strings containing template expressions', () => { - expect(UriTemplate.isTemplate('{foo}')).toBe(true); - expect(UriTemplate.isTemplate('/users/{id}')).toBe(true); - expect(UriTemplate.isTemplate('http://example.com/{path}/{file}')).toBe(true); - expect(UriTemplate.isTemplate('/search{?q,limit}')).toBe(true); - }); - - it('should return false for strings without template expressions', () => { - expect(UriTemplate.isTemplate('')).toBe(false); - expect(UriTemplate.isTemplate('plain string')).toBe(false); - expect(UriTemplate.isTemplate('http://example.com/foo/bar')).toBe(false); - expect(UriTemplate.isTemplate('{}')).toBe(false); // Empty braces don't count - expect(UriTemplate.isTemplate('{ }')).toBe(false); // Just whitespace doesn't count - }); - }); - - describe('simple string expansion', () => { - it('should expand simple string variables', () => { - const template = new UriTemplate('http://example.com/users/{username}'); - expect(template.expand({ username: 'fred' })).toBe('http://example.com/users/fred'); - expect(template.variableNames).toEqual(['username']); - }); - - it('should handle multiple variables', () => { - const template = new UriTemplate('{x,y}'); - expect(template.expand({ x: '1024', y: '768' })).toBe('1024,768'); - expect(template.variableNames).toEqual(['x', 'y']); - }); - - it('should encode reserved characters', () => { - const template = new UriTemplate('{var}'); - expect(template.expand({ var: 'value with spaces' })).toBe('value%20with%20spaces'); - }); - }); - - describe('reserved expansion', () => { - it('should not encode reserved characters with + operator', () => { - const template = new UriTemplate('{+path}/here'); - expect(template.expand({ path: '/foo/bar' })).toBe('/foo/bar/here'); - expect(template.variableNames).toEqual(['path']); - }); - }); - - describe('fragment expansion', () => { - it('should add # prefix and not encode reserved chars', () => { - const template = new UriTemplate('X{#var}'); - expect(template.expand({ var: '/test' })).toBe('X#/test'); - expect(template.variableNames).toEqual(['var']); - }); - }); - - describe('label expansion', () => { - it('should add . prefix', () => { - const template = new UriTemplate('X{.var}'); - expect(template.expand({ var: 'test' })).toBe('X.test'); - expect(template.variableNames).toEqual(['var']); - }); - }); - - describe('path expansion', () => { - it('should add / prefix', () => { - const template = new UriTemplate('X{/var}'); - expect(template.expand({ var: 'test' })).toBe('X/test'); - expect(template.variableNames).toEqual(['var']); - }); - }); - - describe('query expansion', () => { - it('should add ? prefix and name=value format', () => { - const template = new UriTemplate('X{?var}'); - expect(template.expand({ var: 'test' })).toBe('X?var=test'); - expect(template.variableNames).toEqual(['var']); - }); - }); - - describe('form continuation expansion', () => { - it('should add & prefix and name=value format', () => { - const template = new UriTemplate('X{&var}'); - expect(template.expand({ var: 'test' })).toBe('X&var=test'); - expect(template.variableNames).toEqual(['var']); - }); - }); - - describe('matching', () => { - it('should match simple strings and extract variables', () => { - const template = new UriTemplate('http://example.com/users/{username}'); - const match = template.match('http://example.com/users/fred'); - expect(match).toEqual({ username: 'fred' }); - }); - - it('should match multiple variables', () => { - const template = new UriTemplate('/users/{username}/posts/{postId}'); - const match = template.match('/users/fred/posts/123'); - expect(match).toEqual({ username: 'fred', postId: '123' }); - }); - - it('should return null for non-matching URIs', () => { - const template = new UriTemplate('/users/{username}'); - const match = template.match('/posts/123'); - expect(match).toBeNull(); - }); - - it('should handle exploded arrays', () => { - const template = new UriTemplate('{/list*}'); - const match = template.match('/red,green,blue'); - expect(match).toEqual({ list: ['red', 'green', 'blue'] }); - }); - }); - - describe('edge cases', () => { - it('should handle empty variables', () => { - const template = new UriTemplate('{empty}'); - expect(template.expand({})).toBe(''); - expect(template.expand({ empty: '' })).toBe(''); - }); - - it('should handle undefined variables', () => { - const template = new UriTemplate('{a}{b}{c}'); - expect(template.expand({ b: '2' })).toBe('2'); - }); - - it('should handle special characters in variable names', () => { - const template = new UriTemplate('{$var_name}'); - expect(template.expand({ $var_name: 'value' })).toBe('value'); - }); - }); - - describe('complex patterns', () => { - it('should handle nested path segments', () => { - const template = new UriTemplate('/api/{version}/{resource}/{id}'); - expect( - template.expand({ - version: 'v1', - resource: 'users', - id: '123' - }) - ).toBe('/api/v1/users/123'); - expect(template.variableNames).toEqual(['version', 'resource', 'id']); - }); - - it('should handle query parameters with arrays', () => { - const template = new UriTemplate('/search{?tags*}'); - expect( - template.expand({ - tags: ['nodejs', 'typescript', 'testing'] - }) - ).toBe('/search?tags=nodejs,typescript,testing'); - expect(template.variableNames).toEqual(['tags']); - }); - - it('should handle multiple query parameters', () => { - const template = new UriTemplate('/search{?q,page,limit}'); - expect( - template.expand({ - q: 'test', - page: '1', - limit: '10' - }) - ).toBe('/search?q=test&page=1&limit=10'); - expect(template.variableNames).toEqual(['q', 'page', 'limit']); - }); - }); - - describe('matching complex patterns', () => { - it('should match nested path segments', () => { - const template = new UriTemplate('/api/{version}/{resource}/{id}'); - const match = template.match('/api/v1/users/123'); - expect(match).toEqual({ - version: 'v1', - resource: 'users', - id: '123' - }); - expect(template.variableNames).toEqual(['version', 'resource', 'id']); - }); - - it('should match query parameters', () => { - const template = new UriTemplate('/search{?q}'); - const match = template.match('/search?q=test'); - expect(match).toEqual({ q: 'test' }); - expect(template.variableNames).toEqual(['q']); - }); - - it('should match multiple query parameters', () => { - const template = new UriTemplate('/search{?q,page}'); - const match = template.match('/search?q=test&page=1'); - expect(match).toEqual({ q: 'test', page: '1' }); - expect(template.variableNames).toEqual(['q', 'page']); - }); - - it('should handle partial matches correctly', () => { - const template = new UriTemplate('/users/{id}'); - expect(template.match('/users/123/extra')).toBeNull(); - expect(template.match('/users')).toBeNull(); - }); - }); - - describe('security and edge cases', () => { - it('should handle extremely long input strings', () => { - const longString = 'x'.repeat(100000); - const template = new UriTemplate(`/api/{param}`); - expect(template.expand({ param: longString })).toBe(`/api/${longString}`); - expect(template.match(`/api/${longString}`)).toEqual({ param: longString }); - }); - - it('should handle deeply nested template expressions', () => { - const template = new UriTemplate('{a}{b}{c}{d}{e}{f}{g}{h}{i}{j}'.repeat(1000)); - expect(() => - template.expand({ - a: '1', - b: '2', - c: '3', - d: '4', - e: '5', - f: '6', - g: '7', - h: '8', - i: '9', - j: '0' - }) - ).not.toThrow(); - }); - - it('should handle malformed template expressions', () => { - expect(() => new UriTemplate('{unclosed')).toThrow(); - expect(() => new UriTemplate('{}')).not.toThrow(); - expect(() => new UriTemplate('{,}')).not.toThrow(); - expect(() => new UriTemplate('{a}{')).toThrow(); - }); - - it('should handle pathological regex patterns', () => { - const template = new UriTemplate('/api/{param}'); - // Create a string that could cause catastrophic backtracking - const input = '/api/' + 'a'.repeat(100000); - expect(() => template.match(input)).not.toThrow(); - }); - - it('should handle invalid UTF-8 sequences', () => { - const template = new UriTemplate('/api/{param}'); - const invalidUtf8 = '���'; - expect(() => template.expand({ param: invalidUtf8 })).not.toThrow(); - expect(() => template.match(`/api/${invalidUtf8}`)).not.toThrow(); - }); - - it('should handle template/URI length mismatches', () => { - const template = new UriTemplate('/api/{param}'); - expect(template.match('/api/')).toBeNull(); - expect(template.match('/api')).toBeNull(); - expect(template.match('/api/value/extra')).toBeNull(); - }); - - it('should handle repeated operators', () => { - const template = new UriTemplate('{?a}{?b}{?c}'); - expect(template.expand({ a: '1', b: '2', c: '3' })).toBe('?a=1&b=2&c=3'); - expect(template.variableNames).toEqual(['a', 'b', 'c']); - }); - - it('should handle overlapping variable names', () => { - const template = new UriTemplate('{var}{vara}'); - expect(template.expand({ var: '1', vara: '2' })).toBe('12'); - expect(template.variableNames).toEqual(['var', 'vara']); - }); - - it('should handle empty segments', () => { - const template = new UriTemplate('///{a}////{b}////'); - expect(template.expand({ a: '1', b: '2' })).toBe('///1////2////'); - expect(template.match('///1////2////')).toEqual({ a: '1', b: '2' }); - expect(template.variableNames).toEqual(['a', 'b']); - }); - - it('should handle maximum template expression limit', () => { - // Create a template with many expressions - const expressions = Array(10000).fill('{param}').join(''); - expect(() => new UriTemplate(expressions)).not.toThrow(); - }); - - it('should handle maximum variable name length', () => { - const longName = 'a'.repeat(10000); - const template = new UriTemplate(`{${longName}}`); - const vars: Record = {}; - vars[longName] = 'value'; - expect(() => template.expand(vars)).not.toThrow(); - }); - }); -}); diff --git a/typescript-sdk/src/shared/uriTemplate.ts b/typescript-sdk/src/shared/uriTemplate.ts deleted file mode 100644 index 1dd57f5..0000000 --- a/typescript-sdk/src/shared/uriTemplate.ts +++ /dev/null @@ -1,287 +0,0 @@ -// Claude-authored implementation of RFC 6570 URI Templates - -export type Variables = Record; - -const MAX_TEMPLATE_LENGTH = 1000000; // 1MB -const MAX_VARIABLE_LENGTH = 1000000; // 1MB -const MAX_TEMPLATE_EXPRESSIONS = 10000; -const MAX_REGEX_LENGTH = 1000000; // 1MB - -export class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like {foo} or {?bar}. - */ - static isTemplate(str: string): boolean { - // Look for any sequence of characters between curly braces - // that isn't just whitespace - return /\{[^}\s]+\}/.test(str); - } - - private static validateLength(str: string, max: number, context: string): void { - if (str.length > max) { - throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); - } - } - private readonly template: string; - private readonly parts: Array; - - get variableNames(): string[] { - return this.parts.flatMap(part => (typeof part === 'string' ? [] : part.names)); - } - - constructor(template: string) { - UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, 'Template'); - this.template = template; - this.parts = this.parse(template); - } - - toString(): string { - return this.template; - } - - private parse(template: string): Array { - const parts: Array = []; - let currentText = ''; - let i = 0; - let expressionCount = 0; - - while (i < template.length) { - if (template[i] === '{') { - if (currentText) { - parts.push(currentText); - currentText = ''; - } - const end = template.indexOf('}', i); - if (end === -1) throw new Error('Unclosed template expression'); - - expressionCount++; - if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) { - throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); - } - - const expr = template.slice(i + 1, end); - const operator = this.getOperator(expr); - const exploded = expr.includes('*'); - const names = this.getNames(expr); - const name = names[0]; - - // Validate variable name length - for (const name of names) { - UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); - } - - parts.push({ name, operator, names, exploded }); - i = end + 1; - } else { - currentText += template[i]; - i++; - } - } - - if (currentText) { - parts.push(currentText); - } - - return parts; - } - - private getOperator(expr: string): string { - const operators = ['+', '#', '.', '/', '?', '&']; - return operators.find(op => expr.startsWith(op)) || ''; - } - - private getNames(expr: string): string[] { - const operator = this.getOperator(expr); - return expr - .slice(operator.length) - .split(',') - .map(name => name.replace('*', '').trim()) - .filter(name => name.length > 0); - } - - private encodeValue(value: string, operator: string): string { - UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value'); - if (operator === '+' || operator === '#') { - return encodeURI(value); - } - return encodeURIComponent(value); - } - - private expandPart( - part: { - name: string; - operator: string; - names: string[]; - exploded: boolean; - }, - variables: Variables - ): string { - if (part.operator === '?' || part.operator === '&') { - const pairs = part.names - .map(name => { - const value = variables[name]; - if (value === undefined) return ''; - const encoded = Array.isArray(value) - ? value.map(v => this.encodeValue(v, part.operator)).join(',') - : this.encodeValue(value.toString(), part.operator); - return `${name}=${encoded}`; - }) - .filter(pair => pair.length > 0); - - if (pairs.length === 0) return ''; - const separator = part.operator === '?' ? '?' : '&'; - return separator + pairs.join('&'); - } - - if (part.names.length > 1) { - const values = part.names.map(name => variables[name]).filter(v => v !== undefined); - if (values.length === 0) return ''; - return values.map(v => (Array.isArray(v) ? v[0] : v)).join(','); - } - - const value = variables[part.name]; - if (value === undefined) return ''; - - const values = Array.isArray(value) ? value : [value]; - const encoded = values.map(v => this.encodeValue(v, part.operator)); - - switch (part.operator) { - case '': - return encoded.join(','); - case '+': - return encoded.join(','); - case '#': - return '#' + encoded.join(','); - case '.': - return '.' + encoded.join('.'); - case '/': - return '/' + encoded.join('/'); - default: - return encoded.join(','); - } - } - - expand(variables: Variables): string { - let result = ''; - let hasQueryParam = false; - - for (const part of this.parts) { - if (typeof part === 'string') { - result += part; - continue; - } - - const expanded = this.expandPart(part, variables); - if (!expanded) continue; - - // Convert ? to & if we already have a query parameter - if ((part.operator === '?' || part.operator === '&') && hasQueryParam) { - result += expanded.replace('?', '&'); - } else { - result += expanded; - } - - if (part.operator === '?' || part.operator === '&') { - hasQueryParam = true; - } - } - - return result; - } - - private escapeRegExp(str: string): string { - return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - } - - private partToRegExp(part: { - name: string; - operator: string; - names: string[]; - exploded: boolean; - }): Array<{ pattern: string; name: string }> { - const patterns: Array<{ pattern: string; name: string }> = []; - - // Validate variable name length for matching - for (const name of part.names) { - UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); - } - - if (part.operator === '?' || part.operator === '&') { - for (let i = 0; i < part.names.length; i++) { - const name = part.names[i]; - const prefix = i === 0 ? '\\' + part.operator : '&'; - patterns.push({ - pattern: prefix + this.escapeRegExp(name) + '=([^&]+)', - name - }); - } - return patterns; - } - - let pattern: string; - const name = part.name; - - switch (part.operator) { - case '': - pattern = part.exploded ? '([^/]+(?:,[^/]+)*)' : '([^/,]+)'; - break; - case '+': - case '#': - pattern = '(.+)'; - break; - case '.': - pattern = '\\.([^/,]+)'; - break; - case '/': - pattern = '/' + (part.exploded ? '([^/]+(?:,[^/]+)*)' : '([^/,]+)'); - break; - default: - pattern = '([^/]+)'; - } - - patterns.push({ pattern, name }); - return patterns; - } - - match(uri: string): Variables | null { - UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI'); - let pattern = '^'; - const names: Array<{ name: string; exploded: boolean }> = []; - - for (const part of this.parts) { - if (typeof part === 'string') { - pattern += this.escapeRegExp(part); - } else { - const patterns = this.partToRegExp(part); - for (const { pattern: partPattern, name } of patterns) { - pattern += partPattern; - names.push({ name, exploded: part.exploded }); - } - } - } - - pattern += '$'; - UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, 'Generated regex pattern'); - const regex = new RegExp(pattern); - const match = uri.match(regex); - - if (!match) return null; - - const result: Variables = {}; - for (let i = 0; i < names.length; i++) { - const { name, exploded } = names[i]; - const value = match[i + 1]; - const cleanName = name.replace('*', ''); - - if (exploded && value.includes(',')) { - result[cleanName] = value.split(','); - } else { - result[cleanName] = value; - } - } - - return result; - } -} diff --git a/typescript-sdk/src/spec.types.test.ts b/typescript-sdk/src/spec.types.test.ts deleted file mode 100644 index 1f90833..0000000 --- a/typescript-sdk/src/spec.types.test.ts +++ /dev/null @@ -1,493 +0,0 @@ -/** - * This contains: - * - Static type checks to verify the Spec's types are compatible with the SDK's types - * (mutually assignable, w/ slight affordances to get rid of ZodObject.passthrough() index signatures, etc) - * - Runtime checks to verify each Spec type has a static check - * (note: a few don't have SDK types, see MISSING_SDK_TYPES below) - */ -import * as SDKTypes from './types.js'; -import * as SpecTypes from '../spec.types.js'; -import fs from 'node:fs'; - -/* eslint-disable @typescript-eslint/no-unused-vars */ -/* eslint-disable @typescript-eslint/no-unsafe-function-type */ - -// Removes index signatures added by ZodObject.passthrough(). -type RemovePassthrough = T extends object - ? T extends Array - ? Array> - : T extends Function - ? T - : { - [K in keyof T as string extends K ? never : K]: RemovePassthrough; - } - : T; - -// Adds the `jsonrpc` property to a type, to match the on-wire format of notifications. -type WithJSONRPC = T & { jsonrpc: '2.0' }; - -// Adds the `jsonrpc` and `id` properties to a type, to match the on-wire format of requests. -type WithJSONRPCRequest = T & { jsonrpc: '2.0'; id: SDKTypes.RequestId }; - -type IsUnknown = [unknown] extends [T] ? ([T] extends [unknown] ? true : false) : false; - -// Turns {x?: unknown} into {x: unknown} but keeps {_meta?: unknown} unchanged (and leaves other optional properties unchanged, e.g. {x?: string}). -// This works around an apparent quirk of ZodObject.unknown() (makes fields optional) -type MakeUnknownsNotOptional = - IsUnknown extends true - ? unknown - : T extends object - ? T extends Array - ? Array> - : T extends Function - ? T - : Pick & { - // Start with empty object to avoid duplicates - // Make unknown properties required (except _meta) - [K in keyof T as '_meta' extends K ? never : IsUnknown extends true ? K : never]-?: unknown; - } & Pick< - T, - { - // Pick all _meta and non-unknown properties with original modifiers - [K in keyof T]: '_meta' extends K ? K : IsUnknown extends true ? never : K; - }[keyof T] - > & { - // Recurse on the picked properties - [K in keyof Pick< - T, - { - [K in keyof T]: '_meta' extends K ? K : IsUnknown extends true ? never : K; - }[keyof T] - >]: MakeUnknownsNotOptional; - } - : T; - -const sdkTypeChecks = { - CancelledNotification: (sdk: WithJSONRPC, spec: SpecTypes.CancelledNotification) => { - sdk = spec; - spec = sdk; - }, - BaseMetadata: (sdk: RemovePassthrough, spec: SpecTypes.BaseMetadata) => { - sdk = spec; - spec = sdk; - }, - Implementation: (sdk: RemovePassthrough, spec: SpecTypes.Implementation) => { - sdk = spec; - spec = sdk; - }, - ProgressNotification: (sdk: WithJSONRPC, spec: SpecTypes.ProgressNotification) => { - sdk = spec; - spec = sdk; - }, - SubscribeRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.SubscribeRequest) => { - sdk = spec; - spec = sdk; - }, - UnsubscribeRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.UnsubscribeRequest) => { - sdk = spec; - spec = sdk; - }, - PaginatedRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.PaginatedRequest) => { - sdk = spec; - spec = sdk; - }, - PaginatedResult: (sdk: SDKTypes.PaginatedResult, spec: SpecTypes.PaginatedResult) => { - sdk = spec; - spec = sdk; - }, - ListRootsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListRootsRequest) => { - sdk = spec; - spec = sdk; - }, - ListRootsResult: (sdk: RemovePassthrough, spec: SpecTypes.ListRootsResult) => { - sdk = spec; - spec = sdk; - }, - Root: (sdk: RemovePassthrough, spec: SpecTypes.Root) => { - sdk = spec; - spec = sdk; - }, - ElicitRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.ElicitRequest) => { - sdk = spec; - spec = sdk; - }, - ElicitResult: (sdk: RemovePassthrough, spec: SpecTypes.ElicitResult) => { - sdk = spec; - spec = sdk; - }, - CompleteRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.CompleteRequest) => { - sdk = spec; - spec = sdk; - }, - CompleteResult: (sdk: SDKTypes.CompleteResult, spec: SpecTypes.CompleteResult) => { - sdk = spec; - spec = sdk; - }, - ProgressToken: (sdk: SDKTypes.ProgressToken, spec: SpecTypes.ProgressToken) => { - sdk = spec; - spec = sdk; - }, - Cursor: (sdk: SDKTypes.Cursor, spec: SpecTypes.Cursor) => { - sdk = spec; - spec = sdk; - }, - Request: (sdk: SDKTypes.Request, spec: SpecTypes.Request) => { - sdk = spec; - spec = sdk; - }, - Result: (sdk: SDKTypes.Result, spec: SpecTypes.Result) => { - sdk = spec; - spec = sdk; - }, - RequestId: (sdk: SDKTypes.RequestId, spec: SpecTypes.RequestId) => { - sdk = spec; - spec = sdk; - }, - JSONRPCRequest: (sdk: SDKTypes.JSONRPCRequest, spec: SpecTypes.JSONRPCRequest) => { - sdk = spec; - spec = sdk; - }, - JSONRPCNotification: (sdk: SDKTypes.JSONRPCNotification, spec: SpecTypes.JSONRPCNotification) => { - sdk = spec; - spec = sdk; - }, - JSONRPCResponse: (sdk: SDKTypes.JSONRPCResponse, spec: SpecTypes.JSONRPCResponse) => { - sdk = spec; - spec = sdk; - }, - EmptyResult: (sdk: SDKTypes.EmptyResult, spec: SpecTypes.EmptyResult) => { - sdk = spec; - spec = sdk; - }, - Notification: (sdk: SDKTypes.Notification, spec: SpecTypes.Notification) => { - sdk = spec; - spec = sdk; - }, - ClientResult: (sdk: SDKTypes.ClientResult, spec: SpecTypes.ClientResult) => { - sdk = spec; - spec = sdk; - }, - ClientNotification: (sdk: WithJSONRPC, spec: SpecTypes.ClientNotification) => { - sdk = spec; - spec = sdk; - }, - ServerResult: (sdk: SDKTypes.ServerResult, spec: SpecTypes.ServerResult) => { - sdk = spec; - spec = sdk; - }, - ResourceTemplateReference: (sdk: RemovePassthrough, spec: SpecTypes.ResourceTemplateReference) => { - sdk = spec; - spec = sdk; - }, - PromptReference: (sdk: RemovePassthrough, spec: SpecTypes.PromptReference) => { - sdk = spec; - spec = sdk; - }, - ToolAnnotations: (sdk: RemovePassthrough, spec: SpecTypes.ToolAnnotations) => { - sdk = spec; - spec = sdk; - }, - Tool: (sdk: RemovePassthrough, spec: SpecTypes.Tool) => { - sdk = spec; - spec = sdk; - }, - ListToolsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListToolsRequest) => { - sdk = spec; - spec = sdk; - }, - ListToolsResult: (sdk: RemovePassthrough, spec: SpecTypes.ListToolsResult) => { - sdk = spec; - spec = sdk; - }, - CallToolResult: (sdk: RemovePassthrough, spec: SpecTypes.CallToolResult) => { - sdk = spec; - spec = sdk; - }, - CallToolRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CallToolRequest) => { - sdk = spec; - spec = sdk; - }, - ToolListChangedNotification: (sdk: WithJSONRPC, spec: SpecTypes.ToolListChangedNotification) => { - sdk = spec; - spec = sdk; - }, - ResourceListChangedNotification: ( - sdk: WithJSONRPC, - spec: SpecTypes.ResourceListChangedNotification - ) => { - sdk = spec; - spec = sdk; - }, - PromptListChangedNotification: ( - sdk: WithJSONRPC, - spec: SpecTypes.PromptListChangedNotification - ) => { - sdk = spec; - spec = sdk; - }, - RootsListChangedNotification: ( - sdk: WithJSONRPC, - spec: SpecTypes.RootsListChangedNotification - ) => { - sdk = spec; - spec = sdk; - }, - ResourceUpdatedNotification: (sdk: WithJSONRPC, spec: SpecTypes.ResourceUpdatedNotification) => { - sdk = spec; - spec = sdk; - }, - SamplingMessage: (sdk: RemovePassthrough, spec: SpecTypes.SamplingMessage) => { - sdk = spec; - spec = sdk; - }, - CreateMessageResult: (sdk: RemovePassthrough, spec: SpecTypes.CreateMessageResult) => { - sdk = spec; - spec = sdk; - }, - SetLevelRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.SetLevelRequest) => { - sdk = spec; - spec = sdk; - }, - PingRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.PingRequest) => { - sdk = spec; - spec = sdk; - }, - InitializedNotification: (sdk: WithJSONRPC, spec: SpecTypes.InitializedNotification) => { - sdk = spec; - spec = sdk; - }, - ListResourcesRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListResourcesRequest) => { - sdk = spec; - spec = sdk; - }, - ListResourcesResult: (sdk: RemovePassthrough, spec: SpecTypes.ListResourcesResult) => { - sdk = spec; - spec = sdk; - }, - ListResourceTemplatesRequest: ( - sdk: WithJSONRPCRequest, - spec: SpecTypes.ListResourceTemplatesRequest - ) => { - sdk = spec; - spec = sdk; - }, - ListResourceTemplatesResult: ( - sdk: RemovePassthrough, - spec: SpecTypes.ListResourceTemplatesResult - ) => { - sdk = spec; - spec = sdk; - }, - ReadResourceRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ReadResourceRequest) => { - sdk = spec; - spec = sdk; - }, - ReadResourceResult: (sdk: RemovePassthrough, spec: SpecTypes.ReadResourceResult) => { - sdk = spec; - spec = sdk; - }, - ResourceContents: (sdk: RemovePassthrough, spec: SpecTypes.ResourceContents) => { - sdk = spec; - spec = sdk; - }, - TextResourceContents: (sdk: RemovePassthrough, spec: SpecTypes.TextResourceContents) => { - sdk = spec; - spec = sdk; - }, - BlobResourceContents: (sdk: RemovePassthrough, spec: SpecTypes.BlobResourceContents) => { - sdk = spec; - spec = sdk; - }, - Resource: (sdk: RemovePassthrough, spec: SpecTypes.Resource) => { - sdk = spec; - spec = sdk; - }, - ResourceTemplate: (sdk: RemovePassthrough, spec: SpecTypes.ResourceTemplate) => { - sdk = spec; - spec = sdk; - }, - PromptArgument: (sdk: RemovePassthrough, spec: SpecTypes.PromptArgument) => { - sdk = spec; - spec = sdk; - }, - Prompt: (sdk: RemovePassthrough, spec: SpecTypes.Prompt) => { - sdk = spec; - spec = sdk; - }, - ListPromptsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListPromptsRequest) => { - sdk = spec; - spec = sdk; - }, - ListPromptsResult: (sdk: RemovePassthrough, spec: SpecTypes.ListPromptsResult) => { - sdk = spec; - spec = sdk; - }, - GetPromptRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.GetPromptRequest) => { - sdk = spec; - spec = sdk; - }, - TextContent: (sdk: RemovePassthrough, spec: SpecTypes.TextContent) => { - sdk = spec; - spec = sdk; - }, - ImageContent: (sdk: RemovePassthrough, spec: SpecTypes.ImageContent) => { - sdk = spec; - spec = sdk; - }, - AudioContent: (sdk: RemovePassthrough, spec: SpecTypes.AudioContent) => { - sdk = spec; - spec = sdk; - }, - EmbeddedResource: (sdk: RemovePassthrough, spec: SpecTypes.EmbeddedResource) => { - sdk = spec; - spec = sdk; - }, - ResourceLink: (sdk: RemovePassthrough, spec: SpecTypes.ResourceLink) => { - sdk = spec; - spec = sdk; - }, - ContentBlock: (sdk: RemovePassthrough, spec: SpecTypes.ContentBlock) => { - sdk = spec; - spec = sdk; - }, - PromptMessage: (sdk: RemovePassthrough, spec: SpecTypes.PromptMessage) => { - sdk = spec; - spec = sdk; - }, - GetPromptResult: (sdk: RemovePassthrough, spec: SpecTypes.GetPromptResult) => { - sdk = spec; - spec = sdk; - }, - BooleanSchema: (sdk: RemovePassthrough, spec: SpecTypes.BooleanSchema) => { - sdk = spec; - spec = sdk; - }, - StringSchema: (sdk: RemovePassthrough, spec: SpecTypes.StringSchema) => { - sdk = spec; - spec = sdk; - }, - NumberSchema: (sdk: RemovePassthrough, spec: SpecTypes.NumberSchema) => { - sdk = spec; - spec = sdk; - }, - EnumSchema: (sdk: RemovePassthrough, spec: SpecTypes.EnumSchema) => { - sdk = spec; - spec = sdk; - }, - PrimitiveSchemaDefinition: (sdk: RemovePassthrough, spec: SpecTypes.PrimitiveSchemaDefinition) => { - sdk = spec; - spec = sdk; - }, - JSONRPCError: (sdk: SDKTypes.JSONRPCError, spec: SpecTypes.JSONRPCError) => { - sdk = spec; - spec = sdk; - }, - JSONRPCMessage: (sdk: SDKTypes.JSONRPCMessage, spec: SpecTypes.JSONRPCMessage) => { - sdk = spec; - spec = sdk; - }, - CreateMessageRequest: ( - sdk: WithJSONRPCRequest>, - spec: SpecTypes.CreateMessageRequest - ) => { - sdk = spec; - spec = sdk; - }, - InitializeRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.InitializeRequest) => { - sdk = spec; - spec = sdk; - }, - InitializeResult: (sdk: RemovePassthrough, spec: SpecTypes.InitializeResult) => { - sdk = spec; - spec = sdk; - }, - ClientCapabilities: (sdk: RemovePassthrough, spec: SpecTypes.ClientCapabilities) => { - sdk = spec; - spec = sdk; - }, - ServerCapabilities: (sdk: RemovePassthrough, spec: SpecTypes.ServerCapabilities) => { - sdk = spec; - spec = sdk; - }, - ClientRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.ClientRequest) => { - sdk = spec; - spec = sdk; - }, - ServerRequest: (sdk: WithJSONRPCRequest>, spec: SpecTypes.ServerRequest) => { - sdk = spec; - spec = sdk; - }, - LoggingMessageNotification: ( - sdk: MakeUnknownsNotOptional>, - spec: SpecTypes.LoggingMessageNotification - ) => { - sdk = spec; - spec = sdk; - }, - ServerNotification: (sdk: MakeUnknownsNotOptional>, spec: SpecTypes.ServerNotification) => { - sdk = spec; - spec = sdk; - }, - LoggingLevel: (sdk: SDKTypes.LoggingLevel, spec: SpecTypes.LoggingLevel) => { - sdk = spec; - spec = sdk; - }, - Icon: (sdk: RemovePassthrough, spec: SpecTypes.Icon) => { - sdk = spec; - spec = sdk; - }, - Icons: (sdk: RemovePassthrough, spec: SpecTypes.Icons) => { - sdk = spec; - spec = sdk; - } -}; - -// This file is .gitignore'd, and fetched by `npm run fetch:spec-types` (called by `npm run test`) -const SPEC_TYPES_FILE = 'spec.types.ts'; -const SDK_TYPES_FILE = 'src/types.ts'; - -const MISSING_SDK_TYPES = [ - // These are inlined in the SDK: - 'Role', - 'Error', // The inner error object of a JSONRPCError - - // These aren't supported by the SDK yet: - // TODO: Add definitions to the SDK - 'Annotations', - 'ModelHint', - 'ModelPreferences' -]; - -function extractExportedTypes(source: string): string[] { - return [...source.matchAll(/export\s+(?:interface|class|type)\s+(\w+)\b/g)].map(m => m[1]); -} - -describe('Spec Types', () => { - const specTypes = extractExportedTypes(fs.readFileSync(SPEC_TYPES_FILE, 'utf-8')); - const sdkTypes = extractExportedTypes(fs.readFileSync(SDK_TYPES_FILE, 'utf-8')); - const typesToCheck = specTypes.filter(type => !MISSING_SDK_TYPES.includes(type)); - - it('should define some expected types', () => { - expect(specTypes).toContain('JSONRPCNotification'); - expect(specTypes).toContain('ElicitResult'); - expect(specTypes).toHaveLength(94); - }); - - it('should have up to date list of missing sdk types', () => { - for (const typeName of MISSING_SDK_TYPES) { - expect(sdkTypes).not.toContain(typeName); - } - }); - - describe('Compatibility tests', () => { - it.each(typesToCheck)('%s should have a compatibility test', type => { - expect(sdkTypeChecks[type as keyof typeof sdkTypeChecks]).toBeDefined(); - }); - }); - - describe('Missing SDK Types', () => { - it.each(MISSING_SDK_TYPES)('%s should not be present in MISSING_SDK_TYPES if it has a compatibility test', type => { - expect(sdkTypeChecks[type as keyof typeof sdkTypeChecks]).toBeUndefined(); - }); - }); -}); diff --git a/typescript-sdk/src/types.test.ts b/typescript-sdk/src/types.test.ts deleted file mode 100644 index cd8cc07..0000000 --- a/typescript-sdk/src/types.test.ts +++ /dev/null @@ -1,314 +0,0 @@ -import { - LATEST_PROTOCOL_VERSION, - SUPPORTED_PROTOCOL_VERSIONS, - ResourceLinkSchema, - ContentBlockSchema, - PromptMessageSchema, - CallToolResultSchema, - CompleteRequestSchema -} from './types.js'; - -describe('Types', () => { - test('should have correct latest protocol version', () => { - expect(LATEST_PROTOCOL_VERSION).toBeDefined(); - expect(LATEST_PROTOCOL_VERSION).toBe('2025-06-18'); - }); - test('should have correct supported protocol versions', () => { - expect(SUPPORTED_PROTOCOL_VERSIONS).toBeDefined(); - expect(SUPPORTED_PROTOCOL_VERSIONS).toBeInstanceOf(Array); - expect(SUPPORTED_PROTOCOL_VERSIONS).toContain(LATEST_PROTOCOL_VERSION); - expect(SUPPORTED_PROTOCOL_VERSIONS).toContain('2024-11-05'); - expect(SUPPORTED_PROTOCOL_VERSIONS).toContain('2024-10-07'); - expect(SUPPORTED_PROTOCOL_VERSIONS).toContain('2025-03-26'); - }); - - describe('ResourceLink', () => { - test('should validate a minimal ResourceLink', () => { - const resourceLink = { - type: 'resource_link', - uri: 'file:///path/to/file.txt', - name: 'file.txt' - }; - - const result = ResourceLinkSchema.safeParse(resourceLink); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.type).toBe('resource_link'); - expect(result.data.uri).toBe('file:///path/to/file.txt'); - expect(result.data.name).toBe('file.txt'); - } - }); - - test('should validate a ResourceLink with all optional fields', () => { - const resourceLink = { - type: 'resource_link', - uri: 'https://example.com/resource', - name: 'Example Resource', - title: 'A comprehensive example resource', - description: 'This resource demonstrates all fields', - mimeType: 'text/plain', - _meta: { custom: 'metadata' } - }; - - const result = ResourceLinkSchema.safeParse(resourceLink); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.title).toBe('A comprehensive example resource'); - expect(result.data.description).toBe('This resource demonstrates all fields'); - expect(result.data.mimeType).toBe('text/plain'); - expect(result.data._meta).toEqual({ custom: 'metadata' }); - } - }); - - test('should fail validation for invalid type', () => { - const invalidResourceLink = { - type: 'invalid_type', - uri: 'file:///path/to/file.txt', - name: 'file.txt' - }; - - const result = ResourceLinkSchema.safeParse(invalidResourceLink); - expect(result.success).toBe(false); - }); - - test('should fail validation for missing required fields', () => { - const invalidResourceLink = { - type: 'resource_link', - uri: 'file:///path/to/file.txt' - // missing name - }; - - const result = ResourceLinkSchema.safeParse(invalidResourceLink); - expect(result.success).toBe(false); - }); - }); - - describe('ContentBlock', () => { - test('should validate text content', () => { - const textContent = { - type: 'text', - text: 'Hello, world!' - }; - - const result = ContentBlockSchema.safeParse(textContent); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.type).toBe('text'); - } - }); - - test('should validate image content', () => { - const imageContent = { - type: 'image', - data: 'aGVsbG8=', // base64 encoded "hello" - mimeType: 'image/png' - }; - - const result = ContentBlockSchema.safeParse(imageContent); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.type).toBe('image'); - } - }); - - test('should validate audio content', () => { - const audioContent = { - type: 'audio', - data: 'aGVsbG8=', // base64 encoded "hello" - mimeType: 'audio/mp3' - }; - - const result = ContentBlockSchema.safeParse(audioContent); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.type).toBe('audio'); - } - }); - - test('should validate resource link content', () => { - const resourceLink = { - type: 'resource_link', - uri: 'file:///path/to/file.txt', - name: 'file.txt', - mimeType: 'text/plain' - }; - - const result = ContentBlockSchema.safeParse(resourceLink); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.type).toBe('resource_link'); - } - }); - - test('should validate embedded resource content', () => { - const embeddedResource = { - type: 'resource', - resource: { - uri: 'file:///path/to/file.txt', - mimeType: 'text/plain', - text: 'File contents' - } - }; - - const result = ContentBlockSchema.safeParse(embeddedResource); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.type).toBe('resource'); - } - }); - }); - - describe('PromptMessage with ContentBlock', () => { - test('should validate prompt message with resource link', () => { - const promptMessage = { - role: 'assistant', - content: { - type: 'resource_link', - uri: 'file:///project/src/main.rs', - name: 'main.rs', - description: 'Primary application entry point', - mimeType: 'text/x-rust' - } - }; - - const result = PromptMessageSchema.safeParse(promptMessage); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.content.type).toBe('resource_link'); - } - }); - }); - - describe('CallToolResult with ContentBlock', () => { - test('should validate tool result with resource links', () => { - const toolResult = { - content: [ - { - type: 'text', - text: 'Found the following files:' - }, - { - type: 'resource_link', - uri: 'file:///project/src/main.rs', - name: 'main.rs', - description: 'Primary application entry point', - mimeType: 'text/x-rust' - }, - { - type: 'resource_link', - uri: 'file:///project/src/lib.rs', - name: 'lib.rs', - description: 'Library exports', - mimeType: 'text/x-rust' - } - ] - }; - - const result = CallToolResultSchema.safeParse(toolResult); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.content).toHaveLength(3); - expect(result.data.content[0].type).toBe('text'); - expect(result.data.content[1].type).toBe('resource_link'); - expect(result.data.content[2].type).toBe('resource_link'); - } - }); - - test('should validate empty content array with default', () => { - const toolResult = {}; - - const result = CallToolResultSchema.safeParse(toolResult); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.content).toEqual([]); - } - }); - }); - - describe('CompleteRequest', () => { - test('should validate a CompleteRequest without resolved field', () => { - const request = { - method: 'completion/complete', - params: { - ref: { type: 'ref/prompt', name: 'greeting' }, - argument: { name: 'name', value: 'A' } - } - }; - - const result = CompleteRequestSchema.safeParse(request); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.method).toBe('completion/complete'); - expect(result.data.params.ref.type).toBe('ref/prompt'); - expect(result.data.params.context).toBeUndefined(); - } - }); - - test('should validate a CompleteRequest with resolved field', () => { - const request = { - method: 'completion/complete', - params: { - ref: { type: 'ref/resource', uri: 'github://repos/{owner}/{repo}' }, - argument: { name: 'repo', value: 't' }, - context: { - arguments: { - '{owner}': 'microsoft' - } - } - } - }; - - const result = CompleteRequestSchema.safeParse(request); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.params.context?.arguments).toEqual({ - '{owner}': 'microsoft' - }); - } - }); - - test('should validate a CompleteRequest with empty resolved field', () => { - const request = { - method: 'completion/complete', - params: { - ref: { type: 'ref/prompt', name: 'test' }, - argument: { name: 'arg', value: '' }, - context: { - arguments: {} - } - } - }; - - const result = CompleteRequestSchema.safeParse(request); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.params.context?.arguments).toEqual({}); - } - }); - - test('should validate a CompleteRequest with multiple resolved variables', () => { - const request = { - method: 'completion/complete', - params: { - ref: { type: 'ref/resource', uri: 'api://v1/{tenant}/{resource}/{id}' }, - argument: { name: 'id', value: '123' }, - context: { - arguments: { - '{tenant}': 'acme-corp', - '{resource}': 'users' - } - } - } - }; - - const result = CompleteRequestSchema.safeParse(request); - expect(result.success).toBe(true); - if (result.success) { - expect(result.data.params.context?.arguments).toEqual({ - '{tenant}': 'acme-corp', - '{resource}': 'users' - }); - } - }); - }); -}); diff --git a/typescript-sdk/src/types.ts b/typescript-sdk/src/types.ts deleted file mode 100644 index e6d3fe4..0000000 --- a/typescript-sdk/src/types.ts +++ /dev/null @@ -1,1643 +0,0 @@ -import { z, ZodTypeAny } from 'zod'; -import { AuthInfo } from './server/auth/types.js'; - -export const LATEST_PROTOCOL_VERSION = '2025-06-18'; -export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; -export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-03-26', '2024-11-05', '2024-10-07']; - -/* JSON-RPC types */ -export const JSONRPC_VERSION = '2.0'; - -/** - * A progress token, used to associate progress notifications with the original request. - */ -export const ProgressTokenSchema = z.union([z.string(), z.number().int()]); - -/** - * An opaque token used to represent a cursor for pagination. - */ -export const CursorSchema = z.string(); - -const RequestMetaSchema = z - .object({ - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken: z.optional(ProgressTokenSchema) - }) - .passthrough(); - -const BaseRequestParamsSchema = z - .object({ - _meta: z.optional(RequestMetaSchema) - }) - .passthrough(); - -export const RequestSchema = z.object({ - method: z.string(), - params: z.optional(BaseRequestParamsSchema) -}); - -const BaseNotificationParamsSchema = z - .object({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) - }) - .passthrough(); - -export const NotificationSchema = z.object({ - method: z.string(), - params: z.optional(BaseNotificationParamsSchema) -}); - -export const ResultSchema = z - .object({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) - }) - .passthrough(); - -/** - * A uniquely identifying ID for a request in JSON-RPC. - */ -export const RequestIdSchema = z.union([z.string(), z.number().int()]); - -/** - * A request that expects a response. - */ -export const JSONRPCRequestSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema - }) - .merge(RequestSchema) - .strict(); - -export const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest => JSONRPCRequestSchema.safeParse(value).success; - -/** - * A notification which does not expect a response. - */ -export const JSONRPCNotificationSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION) - }) - .merge(NotificationSchema) - .strict(); - -export const isJSONRPCNotification = (value: unknown): value is JSONRPCNotification => JSONRPCNotificationSchema.safeParse(value).success; - -/** - * A successful (non-error) response to a request. - */ -export const JSONRPCResponseSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema - }) - .strict(); - -export const isJSONRPCResponse = (value: unknown): value is JSONRPCResponse => JSONRPCResponseSchema.safeParse(value).success; - -/** - * Error codes defined by the JSON-RPC specification. - */ -export enum ErrorCode { - // SDK error codes - ConnectionClosed = -32000, - RequestTimeout = -32001, - - // Standard JSON-RPC error codes - ParseError = -32700, - InvalidRequest = -32600, - MethodNotFound = -32601, - InvalidParams = -32602, - InternalError = -32603 -} - -/** - * A response to a request that indicates an error occurred. - */ -export const JSONRPCErrorSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - error: z.object({ - /** - * The error type that occurred. - */ - code: z.number().int(), - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: z.string(), - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data: z.optional(z.unknown()) - }) - }) - .strict(); - -export const isJSONRPCError = (value: unknown): value is JSONRPCError => JSONRPCErrorSchema.safeParse(value).success; - -export const JSONRPCMessageSchema = z.union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]); - -/* Empty result */ -/** - * A response that indicates success but carries no data. - */ -export const EmptyResultSchema = ResultSchema.strict(); - -/* Cancellation */ -/** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its `initialize` request. - */ -export const CancelledNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/cancelled'), - params: BaseNotificationParamsSchema.extend({ - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - */ - requestId: RequestIdSchema, - - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason: z.string().optional() - }) -}); - -/* Base Metadata */ -/** - * Icon schema for use in tools, prompts, resources, and implementations. - */ -export const IconSchema = z - .object({ - /** - * URL or data URI for the icon. - */ - src: z.string(), - /** - * Optional MIME type for the icon. - */ - mimeType: z.optional(z.string()), - /** - * Optional array of strings that specify sizes at which the icon can be used. - * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. - * - * If not provided, the client should assume that the icon can be used at any size. - */ - sizes: z.optional(z.array(z.string())) - }) - .passthrough(); - -/** - * Base schema to add `icons` property. - * - */ -export const IconsSchema = z - .object({ - /** - * Optional set of sized icons that the client can display in a user interface. - * - * Clients that support rendering icons MUST support at least the following MIME types: - * - `image/png` - PNG images (safe, universal compatibility) - * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) - * - * Clients that support rendering icons SHOULD also support: - * - `image/svg+xml` - SVG images (scalable but requires security precautions) - * - `image/webp` - WebP images (modern, efficient format) - */ - icons: z.array(IconSchema).optional() - }) - .passthrough(); - -/** - * Base metadata interface for common properties across resources, tools, prompts, and implementations. - */ -export const BaseMetadataSchema = z - .object({ - /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ - name: z.string(), - /** - * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, - * even by those unfamiliar with domain-specific terminology. - * - * If not provided, the name should be used for display (except for Tool, - * where `annotations.title` should be given precedence over using `name`, - * if present). - */ - title: z.optional(z.string()) - }) - .passthrough(); - -/* Initialization */ -/** - * Describes the name and version of an MCP implementation. - */ -export const ImplementationSchema = BaseMetadataSchema.extend({ - version: z.string(), - /** - * An optional URL of the website for this implementation. - */ - websiteUrl: z.optional(z.string()) -}).merge(IconsSchema); - -/** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ -export const ClientCapabilitiesSchema = z - .object({ - /** - * Experimental, non-standard capabilities that the client supports. - */ - experimental: z.optional(z.object({}).passthrough()), - /** - * Present if the client supports sampling from an LLM. - */ - sampling: z.optional(z.object({}).passthrough()), - /** - * Present if the client supports eliciting user input. - */ - elicitation: z.optional(z.object({}).passthrough()), - /** - * Present if the client supports listing roots. - */ - roots: z.optional( - z - .object({ - /** - * Whether the client supports issuing notifications for changes to the roots list. - */ - listChanged: z.optional(z.boolean()) - }) - .passthrough() - ) - }) - .passthrough(); - -/** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ -export const InitializeRequestSchema = RequestSchema.extend({ - method: z.literal('initialize'), - params: BaseRequestParamsSchema.extend({ - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: z.string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema - }) -}); - -export const isInitializeRequest = (value: unknown): value is InitializeRequest => InitializeRequestSchema.safeParse(value).success; - -/** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ -export const ServerCapabilitiesSchema = z - .object({ - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental: z.optional(z.object({}).passthrough()), - /** - * Present if the server supports sending log messages to the client. - */ - logging: z.optional(z.object({}).passthrough()), - /** - * Present if the server supports sending completions to the client. - */ - completions: z.optional(z.object({}).passthrough()), - /** - * Present if the server offers any prompt templates. - */ - prompts: z.optional( - z - .object({ - /** - * Whether this server supports issuing notifications for changes to the prompt list. - */ - listChanged: z.optional(z.boolean()) - }) - .passthrough() - ), - /** - * Present if the server offers any resources to read. - */ - resources: z.optional( - z - .object({ - /** - * Whether this server supports clients subscribing to resource updates. - */ - subscribe: z.optional(z.boolean()), - - /** - * Whether this server supports issuing notifications for changes to the resource list. - */ - listChanged: z.optional(z.boolean()) - }) - .passthrough() - ), - /** - * Present if the server offers any tools to call. - */ - tools: z.optional( - z - .object({ - /** - * Whether this server supports issuing notifications for changes to the tool list. - */ - listChanged: z.optional(z.boolean()) - }) - .passthrough() - ) - }) - .passthrough(); - -/** - * After receiving an initialize request from the client, the server sends this response. - */ -export const InitializeResultSchema = ResultSchema.extend({ - /** - * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. - */ - protocolVersion: z.string(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - /** - * Instructions describing how to use the server and its features. - * - * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. - */ - instructions: z.optional(z.string()) -}); - -/** - * This notification is sent from the client to the server after initialization has finished. - */ -export const InitializedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/initialized') -}); - -export const isInitializedNotification = (value: unknown): value is InitializedNotification => - InitializedNotificationSchema.safeParse(value).success; - -/* Ping */ -/** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ -export const PingRequestSchema = RequestSchema.extend({ - method: z.literal('ping') -}); - -/* Progress notifications */ -export const ProgressSchema = z - .object({ - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - */ - progress: z.number(), - /** - * Total number of items to process (or total progress required), if known. - */ - total: z.optional(z.number()), - /** - * An optional message describing the current progress. - */ - message: z.optional(z.string()) - }) - .passthrough(); - -/** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - */ -export const ProgressNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/progress'), - params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({ - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressTokenSchema - }) -}); - -/* Pagination */ -export const PaginatedRequestSchema = RequestSchema.extend({ - params: BaseRequestParamsSchema.extend({ - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor: z.optional(CursorSchema) - }).optional() -}); - -export const PaginatedResultSchema = ResultSchema.extend({ - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor: z.optional(CursorSchema) -}); - -/* Resources */ -/** - * The contents of a specific resource or sub-resource. - */ -export const ResourceContentsSchema = z - .object({ - /** - * The URI of this resource. - */ - uri: z.string(), - /** - * The MIME type of this resource, if known. - */ - mimeType: z.optional(z.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) - }) - .passthrough(); - -export const TextResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: z.string() -}); - -/** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ -const Base64Schema = z.string().refine( - val => { - try { - // atob throws a DOMException if the string contains characters - // that are not part of the Base64 character set. - atob(val); - return true; - } catch { - return false; - } - }, - { message: 'Invalid Base64 string' } -); - -export const BlobResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * A base64-encoded string representing the binary data of the item. - */ - blob: Base64Schema -}); - -/** - * A known resource that the server is capable of reading. - */ -export const ResourceSchema = BaseMetadataSchema.extend({ - /** - * The URI of this resource. - */ - uri: z.string(), - - /** - * A description of what this resource represents. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: z.optional(z.string()), - - /** - * The MIME type of this resource, if known. - */ - mimeType: z.optional(z.string()), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) -}).merge(IconsSchema); - -/** - * A template description for resources available on the server. - */ -export const ResourceTemplateSchema = BaseMetadataSchema.extend({ - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - */ - uriTemplate: z.string(), - - /** - * A description of what this template is for. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: z.optional(z.string()), - - /** - * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. - */ - mimeType: z.optional(z.string()), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) -}).merge(IconsSchema); - -/** - * Sent from the client to request a list of resources the server has. - */ -export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('resources/list') -}); - -/** - * The server's response to a resources/list request from the client. - */ -export const ListResourcesResultSchema = PaginatedResultSchema.extend({ - resources: z.array(ResourceSchema) -}); - -/** - * Sent from the client to request a list of resource templates the server has. - */ -export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('resources/templates/list') -}); - -/** - * The server's response to a resources/templates/list request from the client. - */ -export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ - resourceTemplates: z.array(ResourceTemplateSchema) -}); - -/** - * Sent from the client to the server, to read a specific resource URI. - */ -export const ReadResourceRequestSchema = RequestSchema.extend({ - method: z.literal('resources/read'), - params: BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. - */ - uri: z.string() - }) -}); - -/** - * The server's response to a resources/read request from the client. - */ -export const ReadResourceResultSchema = ResultSchema.extend({ - contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) -}); - -/** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ -export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/list_changed') -}); - -/** - * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. - */ -export const SubscribeRequestSchema = RequestSchema.extend({ - method: z.literal('resources/subscribe'), - params: BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it. - */ - uri: z.string() - }) -}); - -/** - * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. - */ -export const UnsubscribeRequestSchema = RequestSchema.extend({ - method: z.literal('resources/unsubscribe'), - params: BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to unsubscribe from. - */ - uri: z.string() - }) -}); - -/** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. - */ -export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/updated'), - params: BaseNotificationParamsSchema.extend({ - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - */ - uri: z.string() - }) -}); - -/* Prompts */ -/** - * Describes an argument that a prompt can accept. - */ -export const PromptArgumentSchema = z - .object({ - /** - * The name of the argument. - */ - name: z.string(), - /** - * A human-readable description of the argument. - */ - description: z.optional(z.string()), - /** - * Whether this argument must be provided. - */ - required: z.optional(z.boolean()) - }) - .passthrough(); - -/** - * A prompt or prompt template that the server offers. - */ -export const PromptSchema = BaseMetadataSchema.extend({ - /** - * An optional description of what this prompt provides - */ - description: z.optional(z.string()), - /** - * A list of arguments to use for templating the prompt. - */ - arguments: z.optional(z.array(PromptArgumentSchema)), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) -}).merge(IconsSchema); - -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ -export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('prompts/list') -}); - -/** - * The server's response to a prompts/list request from the client. - */ -export const ListPromptsResultSchema = PaginatedResultSchema.extend({ - prompts: z.array(PromptSchema) -}); - -/** - * Used by the client to get a prompt provided by the server. - */ -export const GetPromptRequestSchema = RequestSchema.extend({ - method: z.literal('prompts/get'), - params: BaseRequestParamsSchema.extend({ - /** - * The name of the prompt or prompt template. - */ - name: z.string(), - /** - * Arguments to use for templating the prompt. - */ - arguments: z.optional(z.record(z.string())) - }) -}); - -/** - * Text provided to or from an LLM. - */ -export const TextContentSchema = z - .object({ - type: z.literal('text'), - /** - * The text content of the message. - */ - text: z.string(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) - }) - .passthrough(); - -/** - * An image provided to or from an LLM. - */ -export const ImageContentSchema = z - .object({ - type: z.literal('image'), - /** - * The base64-encoded image data. - */ - data: Base64Schema, - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: z.string(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) - }) - .passthrough(); - -/** - * An Audio provided to or from an LLM. - */ -export const AudioContentSchema = z - .object({ - type: z.literal('audio'), - /** - * The base64-encoded audio data. - */ - data: Base64Schema, - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: z.string(), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) - }) - .passthrough(); - -/** - * The contents of a resource, embedded into a prompt or tool call result. - */ -export const EmbeddedResourceSchema = z - .object({ - type: z.literal('resource'), - resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) - }) - .passthrough(); - -/** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. - */ -export const ResourceLinkSchema = ResourceSchema.extend({ - type: z.literal('resource_link') -}); - -/** - * A content block that can be used in prompts and tool results. - */ -export const ContentBlockSchema = z.union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); - -/** - * Describes a message returned as part of a prompt. - */ -export const PromptMessageSchema = z - .object({ - role: z.enum(['user', 'assistant']), - content: ContentBlockSchema - }) - .passthrough(); - -/** - * The server's response to a prompts/get request from the client. - */ -export const GetPromptResultSchema = ResultSchema.extend({ - /** - * An optional description for the prompt. - */ - description: z.optional(z.string()), - messages: z.array(PromptMessageSchema) -}); - -/** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -export const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/prompts/list_changed') -}); - -/* Tools */ -/** - * Additional properties describing a Tool to clients. - * - * NOTE: all properties in ToolAnnotations are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on ToolAnnotations - * received from untrusted servers. - */ -export const ToolAnnotationsSchema = z - .object({ - /** - * A human-readable title for the tool. - */ - title: z.optional(z.string()), - - /** - * If true, the tool does not modify its environment. - * - * Default: false - */ - readOnlyHint: z.optional(z.boolean()), - - /** - * If true, the tool may perform destructive updates to its environment. - * If false, the tool performs only additive updates. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: true - */ - destructiveHint: z.optional(z.boolean()), - - /** - * If true, calling the tool repeatedly with the same arguments - * will have no additional effect on the its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: false - */ - idempotentHint: z.optional(z.boolean()), - - /** - * If true, this tool may interact with an "open world" of external - * entities. If false, the tool's domain of interaction is closed. - * For example, the world of a web search tool is open, whereas that - * of a memory tool is not. - * - * Default: true - */ - openWorldHint: z.optional(z.boolean()) - }) - .passthrough(); - -/** - * Definition for a tool the client can call. - */ -export const ToolSchema = BaseMetadataSchema.extend({ - /** - * A human-readable description of the tool. - */ - description: z.optional(z.string()), - /** - * A JSON Schema object defining the expected parameters for the tool. - */ - inputSchema: z - .object({ - type: z.literal('object'), - properties: z.optional(z.object({}).passthrough()), - required: z.optional(z.array(z.string())) - }) - .passthrough(), - /** - * An optional JSON Schema object defining the structure of the tool's output returned in - * the structuredContent field of a CallToolResult. - */ - outputSchema: z.optional( - z - .object({ - type: z.literal('object'), - properties: z.optional(z.object({}).passthrough()), - required: z.optional(z.array(z.string())) - }) - .passthrough() - ), - /** - * Optional additional tool information. - */ - annotations: z.optional(ToolAnnotationsSchema), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) -}).merge(IconsSchema); - -/** - * Sent from the client to request a list of tools the server has. - */ -export const ListToolsRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('tools/list') -}); - -/** - * The server's response to a tools/list request from the client. - */ -export const ListToolsResultSchema = PaginatedResultSchema.extend({ - tools: z.array(ToolSchema) -}); - -/** - * The server's response to a tool call. - */ -export const CallToolResultSchema = ResultSchema.extend({ - /** - * A list of content objects that represent the result of the tool call. - * - * If the Tool does not define an outputSchema, this field MUST be present in the result. - * For backwards compatibility, this field is always present, but it may be empty. - */ - content: z.array(ContentBlockSchema).default([]), - - /** - * An object containing structured tool output. - * - * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. - */ - structuredContent: z.object({}).passthrough().optional(), - - /** - * Whether the tool call ended in an error. - * - * If not set, this is assumed to be false (the call was successful). - * - * Any errors that originate from the tool SHOULD be reported inside the result - * object, with `isError` set to true, _not_ as an MCP protocol-level error - * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. - * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. - */ - isError: z.optional(z.boolean()) -}); - -/** - * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. - */ -export const CompatibilityCallToolResultSchema = CallToolResultSchema.or( - ResultSchema.extend({ - toolResult: z.unknown() - }) -); - -/** - * Used by the client to invoke a tool provided by the server. - */ -export const CallToolRequestSchema = RequestSchema.extend({ - method: z.literal('tools/call'), - params: BaseRequestParamsSchema.extend({ - name: z.string(), - arguments: z.optional(z.record(z.unknown())) - }) -}); - -/** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -export const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/tools/list_changed') -}); - -/* Logging */ -/** - * The severity of a log message. - */ -export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); - -/** - * A request from the client to the server, to enable or adjust logging. - */ -export const SetLevelRequestSchema = RequestSchema.extend({ - method: z.literal('logging/setLevel'), - params: BaseRequestParamsSchema.extend({ - /** - * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. - */ - level: LoggingLevelSchema - }) -}); - -/** - * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. - */ -export const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/message'), - params: BaseNotificationParamsSchema.extend({ - /** - * The severity of this log message. - */ - level: LoggingLevelSchema, - /** - * An optional name of the logger issuing this message. - */ - logger: z.optional(z.string()), - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: z.unknown() - }) -}); - -/* Sampling */ -/** - * Hints to use for model selection. - */ -export const ModelHintSchema = z - .object({ - /** - * A hint for a model name. - */ - name: z.string().optional() - }) - .passthrough(); - -/** - * The server's preferences for model selection, requested of the client during sampling. - */ -export const ModelPreferencesSchema = z - .object({ - /** - * Optional hints to use for model selection. - */ - hints: z.optional(z.array(ModelHintSchema)), - /** - * How much to prioritize cost when selecting a model. - */ - costPriority: z.optional(z.number().min(0).max(1)), - /** - * How much to prioritize sampling speed (latency) when selecting a model. - */ - speedPriority: z.optional(z.number().min(0).max(1)), - /** - * How much to prioritize intelligence and capabilities when selecting a model. - */ - intelligencePriority: z.optional(z.number().min(0).max(1)) - }) - .passthrough(); - -/** - * Describes a message issued to or received from an LLM API. - */ -export const SamplingMessageSchema = z - .object({ - role: z.enum(['user', 'assistant']), - content: z.union([TextContentSchema, ImageContentSchema, AudioContentSchema]) - }) - .passthrough(); - -/** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - */ -export const CreateMessageRequestSchema = RequestSchema.extend({ - method: z.literal('sampling/createMessage'), - params: BaseRequestParamsSchema.extend({ - messages: z.array(SamplingMessageSchema), - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt: z.optional(z.string()), - /** - * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request. - */ - includeContext: z.optional(z.enum(['none', 'thisServer', 'allServers'])), - temperature: z.optional(z.number()), - /** - * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested. - */ - maxTokens: z.number().int(), - stopSequences: z.optional(z.array(z.string())), - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata: z.optional(z.object({}).passthrough()), - /** - * The server's preferences for which model to select. - */ - modelPreferences: z.optional(ModelPreferencesSchema) - }) -}); - -/** - * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. - */ -export const CreateMessageResultSchema = ResultSchema.extend({ - /** - * The name of the model that generated the message. - */ - model: z.string(), - /** - * The reason why sampling stopped. - */ - stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())), - role: z.enum(['user', 'assistant']), - content: z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]) -}); - -/* Elicitation */ -/** - * Primitive schema definition for boolean fields. - */ -export const BooleanSchemaSchema = z - .object({ - type: z.literal('boolean'), - title: z.optional(z.string()), - description: z.optional(z.string()), - default: z.optional(z.boolean()) - }) - .passthrough(); - -/** - * Primitive schema definition for string fields. - */ -export const StringSchemaSchema = z - .object({ - type: z.literal('string'), - title: z.optional(z.string()), - description: z.optional(z.string()), - minLength: z.optional(z.number()), - maxLength: z.optional(z.number()), - format: z.optional(z.enum(['email', 'uri', 'date', 'date-time'])) - }) - .passthrough(); - -/** - * Primitive schema definition for number fields. - */ -export const NumberSchemaSchema = z - .object({ - type: z.enum(['number', 'integer']), - title: z.optional(z.string()), - description: z.optional(z.string()), - minimum: z.optional(z.number()), - maximum: z.optional(z.number()) - }) - .passthrough(); - -/** - * Primitive schema definition for enum fields. - */ -export const EnumSchemaSchema = z - .object({ - type: z.literal('string'), - title: z.optional(z.string()), - description: z.optional(z.string()), - enum: z.array(z.string()), - enumNames: z.optional(z.array(z.string())) - }) - .passthrough(); - -/** - * Union of all primitive schema definitions. - */ -export const PrimitiveSchemaDefinitionSchema = z.union([BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, EnumSchemaSchema]); - -/** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user. - */ -export const ElicitRequestSchema = RequestSchema.extend({ - method: z.literal('elicitation/create'), - params: BaseRequestParamsSchema.extend({ - /** - * The message to present to the user. - */ - message: z.string(), - /** - * The schema for the requested user input. - */ - requestedSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), - required: z.optional(z.array(z.string())) - }) - .passthrough() - }) -}); - -/** - * The client's response to an elicitation/create request from the server. - */ -export const ElicitResultSchema = ResultSchema.extend({ - /** - * The user's response action. - */ - action: z.enum(['accept', 'decline', 'cancel']), - /** - * The collected user input content (only present if action is "accept"). - */ - content: z.optional(z.record(z.string(), z.unknown())) -}); - -/* Autocomplete */ -/** - * A reference to a resource or resource template definition. - */ -export const ResourceTemplateReferenceSchema = z - .object({ - type: z.literal('ref/resource'), - /** - * The URI or URI template of the resource. - */ - uri: z.string() - }) - .passthrough(); - -/** - * @deprecated Use ResourceTemplateReferenceSchema instead - */ -export const ResourceReferenceSchema = ResourceTemplateReferenceSchema; - -/** - * Identifies a prompt. - */ -export const PromptReferenceSchema = z - .object({ - type: z.literal('ref/prompt'), - /** - * The name of the prompt or prompt template - */ - name: z.string() - }) - .passthrough(); - -/** - * A request from the client to the server, to ask for completion options. - */ -export const CompleteRequestSchema = RequestSchema.extend({ - method: z.literal('completion/complete'), - params: BaseRequestParamsSchema.extend({ - ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - /** - * The argument's information - */ - argument: z - .object({ - /** - * The name of the argument - */ - name: z.string(), - /** - * The value of the argument to use for completion matching. - */ - value: z.string() - }) - .passthrough(), - context: z.optional( - z.object({ - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments: z.optional(z.record(z.string(), z.string())) - }) - ) - }) -}); - -/** - * The server's response to a completion/complete request - */ -export const CompleteResultSchema = ResultSchema.extend({ - completion: z - .object({ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: z.array(z.string()).max(100), - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: z.optional(z.number().int()), - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: z.optional(z.boolean()) - }) - .passthrough() -}); - -/* Roots */ -/** - * Represents a root directory or file that the server can operate on. - */ -export const RootSchema = z - .object({ - /** - * The URI identifying the root. This *must* start with file:// for now. - */ - uri: z.string().startsWith('file://'), - /** - * An optional name for the root. - */ - name: z.optional(z.string()), - - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) - }) - .passthrough(); - -/** - * Sent from the server to request a list of root URIs from the client. - */ -export const ListRootsRequestSchema = RequestSchema.extend({ - method: z.literal('roots/list') -}); - -/** - * The client's response to a roots/list request from the server. - */ -export const ListRootsResultSchema = ResultSchema.extend({ - roots: z.array(RootSchema) -}); - -/** - * A notification from the client to the server, informing it that the list of roots has changed. - */ -export const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/roots/list_changed') -}); - -/* Client messages */ -export const ClientRequestSchema = z.union([ - PingRequestSchema, - InitializeRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema -]); - -export const ClientNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - InitializedNotificationSchema, - RootsListChangedNotificationSchema -]); - -export const ClientResultSchema = z.union([EmptyResultSchema, CreateMessageResultSchema, ElicitResultSchema, ListRootsResultSchema]); - -/* Server messages */ -export const ServerRequestSchema = z.union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]); - -export const ServerNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema -]); - -export const ServerResultSchema = z.union([ - EmptyResultSchema, - InitializeResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - CallToolResultSchema, - ListToolsResultSchema -]); - -export class McpError extends Error { - constructor( - public readonly code: number, - message: string, - public readonly data?: unknown - ) { - super(`MCP error ${code}: ${message}`); - this.name = 'McpError'; - } -} - -type Primitive = string | number | boolean | bigint | null | undefined; -type Flatten = T extends Primitive - ? T - : T extends Array - ? Array> - : T extends Set - ? Set> - : T extends Map - ? Map, Flatten> - : T extends object - ? { [K in keyof T]: Flatten } - : T; - -type Infer = Flatten>; - -/** - * Headers that are compatible with both Node.js and the browser. - */ -export type IsomorphicHeaders = Record; - -/** - * Information about the incoming request. - */ -export interface RequestInfo { - /** - * The headers of the request. - */ - headers: IsomorphicHeaders; -} - -/** - * Extra information about a message. - */ -export interface MessageExtraInfo { - /** - * The request information. - */ - requestInfo?: RequestInfo; - - /** - * The authentication information. - */ - authInfo?: AuthInfo; -} - -/* JSON-RPC types */ -export type ProgressToken = Infer; -export type Cursor = Infer; -export type Request = Infer; -export type RequestMeta = Infer; -export type Notification = Infer; -export type Result = Infer; -export type RequestId = Infer; -export type JSONRPCRequest = Infer; -export type JSONRPCNotification = Infer; -export type JSONRPCResponse = Infer; -export type JSONRPCError = Infer; -export type JSONRPCMessage = Infer; - -/* Empty result */ -export type EmptyResult = Infer; - -/* Cancellation */ -export type CancelledNotification = Infer; - -/* Base Metadata */ -export type Icon = Infer; -export type Icons = Infer; -export type BaseMetadata = Infer; - -/* Initialization */ -export type Implementation = Infer; -export type ClientCapabilities = Infer; -export type InitializeRequest = Infer; -export type ServerCapabilities = Infer; -export type InitializeResult = Infer; -export type InitializedNotification = Infer; - -/* Ping */ -export type PingRequest = Infer; - -/* Progress notifications */ -export type Progress = Infer; -export type ProgressNotification = Infer; - -/* Pagination */ -export type PaginatedRequest = Infer; -export type PaginatedResult = Infer; - -/* Resources */ -export type ResourceContents = Infer; -export type TextResourceContents = Infer; -export type BlobResourceContents = Infer; -export type Resource = Infer; -export type ResourceTemplate = Infer; -export type ListResourcesRequest = Infer; -export type ListResourcesResult = Infer; -export type ListResourceTemplatesRequest = Infer; -export type ListResourceTemplatesResult = Infer; -export type ReadResourceRequest = Infer; -export type ReadResourceResult = Infer; -export type ResourceListChangedNotification = Infer; -export type SubscribeRequest = Infer; -export type UnsubscribeRequest = Infer; -export type ResourceUpdatedNotification = Infer; - -/* Prompts */ -export type PromptArgument = Infer; -export type Prompt = Infer; -export type ListPromptsRequest = Infer; -export type ListPromptsResult = Infer; -export type GetPromptRequest = Infer; -export type TextContent = Infer; -export type ImageContent = Infer; -export type AudioContent = Infer; -export type EmbeddedResource = Infer; -export type ResourceLink = Infer; -export type ContentBlock = Infer; -export type PromptMessage = Infer; -export type GetPromptResult = Infer; -export type PromptListChangedNotification = Infer; - -/* Tools */ -export type ToolAnnotations = Infer; -export type Tool = Infer; -export type ListToolsRequest = Infer; -export type ListToolsResult = Infer; -export type CallToolResult = Infer; -export type CompatibilityCallToolResult = Infer; -export type CallToolRequest = Infer; -export type ToolListChangedNotification = Infer; - -/* Logging */ -export type LoggingLevel = Infer; -export type SetLevelRequest = Infer; -export type LoggingMessageNotification = Infer; - -/* Sampling */ -export type SamplingMessage = Infer; -export type CreateMessageRequest = Infer; -export type CreateMessageResult = Infer; - -/* Elicitation */ -export type BooleanSchema = Infer; -export type StringSchema = Infer; -export type NumberSchema = Infer; -export type EnumSchema = Infer; -export type PrimitiveSchemaDefinition = Infer; -export type ElicitRequest = Infer; -export type ElicitResult = Infer; - -/* Autocomplete */ -export type ResourceTemplateReference = Infer; -/** - * @deprecated Use ResourceTemplateReference instead - */ -export type ResourceReference = ResourceTemplateReference; -export type PromptReference = Infer; -export type CompleteRequest = Infer; -export type CompleteResult = Infer; - -/* Roots */ -export type Root = Infer; -export type ListRootsRequest = Infer; -export type ListRootsResult = Infer; -export type RootsListChangedNotification = Infer; - -/* Client messages */ -export type ClientRequest = Infer; -export type ClientNotification = Infer; -export type ClientResult = Infer; - -/* Server messages */ -export type ServerRequest = Infer; -export type ServerNotification = Infer; -export type ServerResult = Infer; diff --git a/typescript-sdk/src/validation/ajv-provider.ts b/typescript-sdk/src/validation/ajv-provider.ts deleted file mode 100644 index 115a985..0000000 --- a/typescript-sdk/src/validation/ajv-provider.ts +++ /dev/null @@ -1,97 +0,0 @@ -/** - * AJV-based JSON Schema validator provider - */ - -import { Ajv } from 'ajv'; -import _addFormats from 'ajv-formats'; -import type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; - -function createDefaultAjvInstance(): Ajv { - const ajv = new Ajv({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - - const addFormats = _addFormats as unknown as typeof _addFormats.default; - addFormats(ajv); - - return ajv; -} - -/** - * @example - * ```typescript - * // Use with default AJV instance (recommended) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Use with custom AJV instance - * import { Ajv } from 'ajv'; - * const ajv = new Ajv({ strict: true, allErrors: true }); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ -export class AjvJsonSchemaValidator implements jsonSchemaValidator { - private _ajv: Ajv; - - /** - * Create an AJV validator - * - * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. - * - * @example - * ```typescript - * // Use default configuration (recommended for most cases) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Or provide custom AJV instance for advanced configuration - * import { Ajv } from 'ajv'; - * import addFormats from 'ajv-formats'; - * - * const ajv = new Ajv({ validateFormats: true }); - * addFormats(ajv); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ - constructor(ajv?: Ajv) { - this._ajv = ajv ?? createDefaultAjvInstance(); - } - - /** - * Create a validator for the given JSON Schema - * - * The validator is compiled once and can be reused multiple times. - * If the schema has an $id, it will be cached by AJV automatically. - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema: JsonSchemaType): JsonSchemaValidator { - // Check if schema has $id and is already compiled/cached - const ajvValidator = - '$id' in schema && typeof schema.$id === 'string' - ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema)) - : this._ajv.compile(schema); - - return (input: unknown): JsonSchemaValidatorResult => { - const valid = ajvValidator(input); - - if (valid) { - return { - valid: true, - data: input as T, - errorMessage: undefined - }; - } else { - return { - valid: false, - data: undefined, - errorMessage: this._ajv.errorsText(ajvValidator.errors) - }; - } - }; - } -} diff --git a/typescript-sdk/src/validation/cfworker-provider.ts b/typescript-sdk/src/validation/cfworker-provider.ts deleted file mode 100644 index 60ec3f0..0000000 --- a/typescript-sdk/src/validation/cfworker-provider.ts +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Cloudflare Worker-compatible JSON Schema validator provider - * - * This provider uses @cfworker/json-schema for validation without code generation, - * making it compatible with edge runtimes like Cloudflare Workers that restrict - * eval and new Function. - * - */ - -import { type Schema, Validator } from '@cfworker/json-schema'; -import type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; - -/** - * JSON Schema draft version supported by @cfworker/json-schema - */ -export type CfWorkerSchemaDraft = '4' | '7' | '2019-09' | '2020-12'; - -/** - * - * @example - * ```typescript - * // Use with default configuration (2020-12, shortcircuit) - * const validator = new CfWorkerJsonSchemaValidator(); - * - * // Use with custom configuration - * const validator = new CfWorkerJsonSchemaValidator({ - * draft: '2020-12', - * shortcircuit: false // Report all errors - * }); - * ``` - */ -export class CfWorkerJsonSchemaValidator implements jsonSchemaValidator { - private shortcircuit: boolean; - private draft: CfWorkerSchemaDraft; - - /** - * Create a validator - * - * @param options - Configuration options - * @param options.shortcircuit - If true, stop validation after first error (default: true) - * @param options.draft - JSON Schema draft version to use (default: '2020-12') - */ - constructor(options?: { shortcircuit?: boolean; draft?: CfWorkerSchemaDraft }) { - this.shortcircuit = options?.shortcircuit ?? true; - this.draft = options?.draft ?? '2020-12'; - } - - /** - * Create a validator for the given JSON Schema - * - * Unlike AJV, this validator is not cached internally - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema: JsonSchemaType): JsonSchemaValidator { - const cfSchema = schema as unknown as Schema; - const validator = new Validator(cfSchema, this.draft, this.shortcircuit); - - return (input: unknown): JsonSchemaValidatorResult => { - const result = validator.validate(input); - - if (result.valid) { - return { - valid: true, - data: input as T, - errorMessage: undefined - }; - } else { - return { - valid: false, - data: undefined, - errorMessage: result.errors.map(err => `${err.instanceLocation}: ${err.error}`).join('; ') - }; - } - }; - } -} diff --git a/typescript-sdk/src/validation/index.ts b/typescript-sdk/src/validation/index.ts deleted file mode 100644 index a6df86d..0000000 --- a/typescript-sdk/src/validation/index.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * JSON Schema validation - * - * This module provides configurable JSON Schema validation for the MCP SDK. - * Choose a validator based on your runtime environment: - * - * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) - * Import from: @modelcontextprotocol/sdk/validation/ajv - * Requires peer dependencies: ajv, ajv-formats - * - * - CfWorkerJsonSchemaValidator: Best for edge runtimes - * Import from: @modelcontextprotocol/sdk/validation/cfworker - * Requires peer dependency: @cfworker/json-schema - * - * @example - * ```typescript - * // For Node.js with AJV - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // For Cloudflare Workers - * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; - * const validator = new CfWorkerJsonSchemaValidator(); - * ``` - * - * @module validation - */ - -// Core types only - implementations are exported via separate entry points -export type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; diff --git a/typescript-sdk/src/validation/types.ts b/typescript-sdk/src/validation/types.ts deleted file mode 100644 index c540b59..0000000 --- a/typescript-sdk/src/validation/types.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type { Schema } from '@cfworker/json-schema'; - -/** - * Result of a JSON Schema validation operation - */ -export type JsonSchemaValidatorResult = - | { valid: true; data: T; errorMessage: undefined } - | { valid: false; data: undefined; errorMessage: string }; - -/** - * A validator function that validates data against a JSON Schema - */ -export type JsonSchemaValidator = (input: unknown) => JsonSchemaValidatorResult; - -/** - * Provider interface for creating validators from JSON Schemas - * - * This is the main extension point for custom validator implementations. - * Implementations should: - * - Support JSON Schema Draft 2020-12 (or be compatible with it) - * - Return validator functions that can be called multiple times - * - Handle schema compilation/caching internally - * - Provide clear error messages on validation failure - * - * @example - * ```typescript - * class MyValidatorProvider implements jsonSchemaValidator { - * getValidator(schema: JsonSchemaType): JsonSchemaValidator { - * // Compile/cache validator from schema - * return (input: unknown) => { - * // Validate input against schema - * if (valid) { - * return { valid: true, data: input as T, errorMessage: undefined }; - * } else { - * return { valid: false, data: undefined, errorMessage: 'Error details' }; - * } - * }; - * } - * } - * ``` - */ -export interface jsonSchemaValidator { - /** - * Create a validator for the given JSON Schema - * - * @param schema - Standard JSON Schema object - * @returns A validator function that can be called multiple times - */ - getValidator(schema: JsonSchemaType): JsonSchemaValidator; -} - -export type JsonSchemaType = Schema; diff --git a/typescript-sdk/src/validation/validation.test.ts b/typescript-sdk/src/validation/validation.test.ts deleted file mode 100644 index ef2e770..0000000 --- a/typescript-sdk/src/validation/validation.test.ts +++ /dev/null @@ -1,623 +0,0 @@ -/** - * Tests all validator providers with various JSON Schema 2020-12 features - * Based on MCP specification for elicitation schemas: - * https://modelcontextprotocol.io/specification/draft/client/elicitation.md - */ - -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; - -import { AjvJsonSchemaValidator } from './ajv-provider.js'; -import { CfWorkerJsonSchemaValidator } from './cfworker-provider.js'; -import type { JsonSchemaType } from './types.js'; - -// Test with both AJV and CfWorker validators -// AJV validator will use default configuration with format validation enabled -const validators = [ - { name: 'AJV', provider: new AjvJsonSchemaValidator() }, - { name: 'CfWorker', provider: new CfWorkerJsonSchemaValidator() } -]; - -describe('JSON Schema Validators', () => { - describe.each(validators)('$name Validator', ({ provider }) => { - describe('String schemas', () => { - it('validates basic string', () => { - const schema: JsonSchemaType = { - type: 'string' - }; - const validator = provider.getValidator(schema); - - const validResult = validator('hello'); - expect(validResult.valid).toBe(true); - expect(validResult.data).toBe('hello'); - - const invalidResult = validator(123); - expect(invalidResult.valid).toBe(false); - expect(invalidResult.errorMessage).toBeDefined(); - }); - - it('validates string with title and description', () => { - const schema: JsonSchemaType = { - type: 'string', - title: 'Name', - description: "User's full name" - }; - const validator = provider.getValidator(schema); - - const result = validator('John Doe'); - expect(result.valid).toBe(true); - expect(result.data).toBe('John Doe'); - }); - - it('validates string with length constraints', () => { - const schema: JsonSchemaType = { - type: 'string', - minLength: 3, - maxLength: 10 - }; - const validator = provider.getValidator(schema); - - expect(validator('abc').valid).toBe(true); - expect(validator('abcdefghij').valid).toBe(true); - expect(validator('ab').valid).toBe(false); - expect(validator('abcdefghijk').valid).toBe(false); - }); - - it('validates email format', () => { - const schema: JsonSchemaType = { - type: 'string', - format: 'email' - }; - const validator = provider.getValidator(schema); - - expect(validator('user@example.com').valid).toBe(true); - expect(validator('invalid-email').valid).toBe(false); - }); - - it('validates URI format', () => { - const schema: JsonSchemaType = { - type: 'string', - format: 'uri' - }; - const validator = provider.getValidator(schema); - - expect(validator('https://example.com').valid).toBe(true); - expect(validator('not-a-uri').valid).toBe(false); - }); - - it('validates date-time format', () => { - const schema: JsonSchemaType = { - type: 'string', - format: 'date-time' - }; - const validator = provider.getValidator(schema); - - expect(validator('2025-10-17T12:00:00Z').valid).toBe(true); - expect(validator('not-a-date').valid).toBe(false); - }); - - it('validates string pattern', () => { - const schema: JsonSchemaType = { - type: 'string', - pattern: '^[A-Z]{3}$' - }; - const validator = provider.getValidator(schema); - - expect(validator('ABC').valid).toBe(true); - expect(validator('abc').valid).toBe(false); - expect(validator('ABCD').valid).toBe(false); - }); - }); - - describe('Number schemas', () => { - it('validates number type', () => { - const schema: JsonSchemaType = { - type: 'number' - }; - const validator = provider.getValidator(schema); - - expect(validator(42).valid).toBe(true); - expect(validator(3.14).valid).toBe(true); - expect(validator('42').valid).toBe(false); - }); - - it('validates integer type', () => { - const schema: JsonSchemaType = { - type: 'integer' - }; - const validator = provider.getValidator(schema); - - expect(validator(42).valid).toBe(true); - expect(validator(3.14).valid).toBe(false); - }); - - it('validates number range', () => { - const schema: JsonSchemaType = { - type: 'number', - minimum: 0, - maximum: 100 - }; - const validator = provider.getValidator(schema); - - expect(validator(0).valid).toBe(true); - expect(validator(50).valid).toBe(true); - expect(validator(100).valid).toBe(true); - expect(validator(-1).valid).toBe(false); - expect(validator(101).valid).toBe(false); - }); - }); - - describe('Boolean schemas', () => { - it('validates boolean type', () => { - const schema: JsonSchemaType = { - type: 'boolean' - }; - const validator = provider.getValidator(schema); - - expect(validator(true).valid).toBe(true); - expect(validator(false).valid).toBe(true); - expect(validator('true').valid).toBe(false); - expect(validator(1).valid).toBe(false); - }); - - it('validates boolean with default', () => { - const schema: JsonSchemaType = { - type: 'boolean', - default: false - }; - const validator = provider.getValidator(schema); - - expect(validator(true).valid).toBe(true); - expect(validator(false).valid).toBe(true); - }); - }); - - describe('Enum schemas', () => { - it('validates enum values', () => { - const schema: JsonSchemaType = { - enum: ['red', 'green', 'blue'] - }; - const validator = provider.getValidator(schema); - - expect(validator('red').valid).toBe(true); - expect(validator('green').valid).toBe(true); - expect(validator('blue').valid).toBe(true); - expect(validator('yellow').valid).toBe(false); - }); - - it('validates enum with mixed types', () => { - const schema: JsonSchemaType = { - enum: ['option1', 42, true, null] - }; - const validator = provider.getValidator(schema); - - expect(validator('option1').valid).toBe(true); - expect(validator(42).valid).toBe(true); - expect(validator(true).valid).toBe(true); - expect(validator(null).valid).toBe(true); - expect(validator('other').valid).toBe(false); - }); - }); - - describe('Object schemas', () => { - it('validates simple object', () => { - const schema: JsonSchemaType = { - type: 'object', - properties: { - name: { type: 'string' }, - age: { type: 'number' } - }, - required: ['name'] - }; - const validator = provider.getValidator(schema); - - expect(validator({ name: 'John', age: 30 }).valid).toBe(true); - expect(validator({ name: 'John' }).valid).toBe(true); - expect(validator({ age: 30 }).valid).toBe(false); - expect(validator({}).valid).toBe(false); - }); - - it('validates nested objects', () => { - const schema: JsonSchemaType = { - type: 'object', - properties: { - user: { - type: 'object', - properties: { - name: { type: 'string' }, - email: { type: 'string', format: 'email' } - }, - required: ['name'] - } - }, - required: ['user'] - }; - const validator = provider.getValidator(schema); - - expect( - validator({ - user: { name: 'John', email: 'john@example.com' } - }).valid - ).toBe(true); - - expect( - validator({ - user: { name: 'John' } - }).valid - ).toBe(true); - - expect( - validator({ - user: { email: 'john@example.com' } - }).valid - ).toBe(false); - }); - - it('validates object with additionalProperties: false', () => { - const schema: JsonSchemaType = { - type: 'object', - properties: { - name: { type: 'string' } - }, - additionalProperties: false - }; - const validator = provider.getValidator(schema); - - expect(validator({ name: 'John' }).valid).toBe(true); - expect(validator({ name: 'John', extra: 'field' }).valid).toBe(false); - }); - }); - - describe('Array schemas', () => { - it('validates array of strings', () => { - const schema: JsonSchemaType = { - type: 'array', - items: { type: 'string' } - }; - const validator = provider.getValidator(schema); - - expect(validator(['a', 'b', 'c']).valid).toBe(true); - expect(validator([]).valid).toBe(true); - expect(validator(['a', 1, 'c']).valid).toBe(false); - }); - - it('validates array length constraints', () => { - const schema: JsonSchemaType = { - type: 'array', - items: { type: 'number' }, - minItems: 1, - maxItems: 3 - }; - const validator = provider.getValidator(schema); - - expect(validator([1]).valid).toBe(true); - expect(validator([1, 2, 3]).valid).toBe(true); - expect(validator([]).valid).toBe(false); - expect(validator([1, 2, 3, 4]).valid).toBe(false); - }); - - it('validates array with unique items', () => { - const schema: JsonSchemaType = { - type: 'array', - items: { type: 'number' }, - uniqueItems: true - }; - const validator = provider.getValidator(schema); - - expect(validator([1, 2, 3]).valid).toBe(true); - expect(validator([1, 2, 2, 3]).valid).toBe(false); - }); - }); - - describe('JSON Schema 2020-12 features', () => { - it('validates schema with $schema field', () => { - const schema: JsonSchemaType = { - $schema: 'https://json-schema.org/draft/2020-12/schema', - type: 'string' - }; - const validator = provider.getValidator(schema); - - expect(validator('test').valid).toBe(true); - }); - - it('validates schema with $id field', () => { - const schema: JsonSchemaType = { - $id: 'https://example.com/schemas/test', - type: 'number' - }; - const validator = provider.getValidator(schema); - - expect(validator(42).valid).toBe(true); - }); - - it('validates with allOf', () => { - const schema: JsonSchemaType = { - allOf: [ - { type: 'object', properties: { name: { type: 'string' } } }, - { type: 'object', properties: { age: { type: 'number' } } } - ] - }; - const validator = provider.getValidator(schema); - - expect(validator({ name: 'John', age: 30 }).valid).toBe(true); - expect(validator({ name: 'John' }).valid).toBe(true); - expect(validator({ name: 123 }).valid).toBe(false); - }); - - it('validates with anyOf', () => { - const schema: JsonSchemaType = { - anyOf: [{ type: 'string' }, { type: 'number' }] - }; - const validator = provider.getValidator(schema); - - expect(validator('test').valid).toBe(true); - expect(validator(42).valid).toBe(true); - expect(validator(true).valid).toBe(false); - }); - - it('validates with oneOf', () => { - const schema: JsonSchemaType = { - oneOf: [ - { type: 'string', minLength: 5 }, - { type: 'string', maxLength: 3 } - ] - }; - const validator = provider.getValidator(schema); - - expect(validator('ab').valid).toBe(true); // Matches second only - expect(validator('hello').valid).toBe(true); // Matches first only - expect(validator('abcd').valid).toBe(false); // Matches neither - }); - - it('validates with not', () => { - const schema: JsonSchemaType = { - not: { type: 'null' } - }; - const validator = provider.getValidator(schema); - - expect(validator('test').valid).toBe(true); - expect(validator(42).valid).toBe(true); - expect(validator(null).valid).toBe(false); - }); - - it('validates with const', () => { - const schema: JsonSchemaType = { - const: 'specific-value' - }; - const validator = provider.getValidator(schema); - - expect(validator('specific-value').valid).toBe(true); - expect(validator('other-value').valid).toBe(false); - }); - }); - - describe('Complex real-world schemas', () => { - it('validates user registration form', () => { - const schema: JsonSchemaType = { - type: 'object', - properties: { - username: { - type: 'string', - minLength: 3, - maxLength: 20, - pattern: '^[a-zA-Z0-9_]+$' - }, - email: { - type: 'string', - format: 'email' - }, - age: { - type: 'integer', - minimum: 18, - maximum: 120 - }, - newsletter: { - type: 'boolean', - default: false - } - }, - required: ['username', 'email'] - }; - const validator = provider.getValidator(schema); - - expect( - validator({ - username: 'john_doe', - email: 'john@example.com', - age: 25, - newsletter: true - }).valid - ).toBe(true); - - expect( - validator({ - username: 'john_doe', - email: 'john@example.com' - }).valid - ).toBe(true); - - expect( - validator({ - username: 'ab', // Too short - email: 'john@example.com' - }).valid - ).toBe(false); - - expect( - validator({ - username: 'john_doe', - email: 'invalid-email' - }).valid - ).toBe(false); - }); - - it('validates API response with nested structure', () => { - const schema: JsonSchemaType = { - type: 'object', - properties: { - status: { - type: 'string', - enum: ['success', 'error', 'pending'] - }, - data: { - type: 'object', - properties: { - id: { type: 'string' }, - items: { - type: 'array', - items: { - type: 'object', - properties: { - name: { type: 'string' }, - quantity: { type: 'integer', minimum: 1 } - }, - required: ['name', 'quantity'] - } - } - }, - required: ['id', 'items'] - }, - timestamp: { - type: 'string', - format: 'date-time' - } - }, - required: ['status', 'data'] - }; - const validator = provider.getValidator(schema); - - expect( - validator({ - status: 'success', - data: { - id: '123', - items: [ - { name: 'Item 1', quantity: 5 }, - { name: 'Item 2', quantity: 3 } - ] - }, - timestamp: '2025-10-17T12:00:00Z' - }).valid - ).toBe(true); - - expect( - validator({ - status: 'invalid-status', - data: { id: '123', items: [] } - }).valid - ).toBe(false); - }); - }); - - describe('Error messages', () => { - it('provides helpful error message on validation failure', () => { - const schema: JsonSchemaType = { - type: 'object', - properties: { - name: { type: 'string' } - }, - required: ['name'] - }; - const validator = provider.getValidator(schema); - - const result = validator({}); - expect(result.valid).toBe(false); - expect(result.errorMessage).toBeDefined(); - expect(result.errorMessage).toBeTruthy(); - expect(typeof result.errorMessage).toBe('string'); - }); - }); - }); -}); - -describe('Missing dependencies', () => { - describe('AJV not installed but CfWorker is', () => { - beforeEach(() => { - jest.resetModules(); - }); - - afterEach(() => { - jest.unmock('ajv'); - jest.unmock('ajv-formats'); - }); - - it('should throw error when trying to import ajv-provider without ajv', async () => { - // Mock ajv as not installed - jest.doMock('ajv', () => { - throw new Error("Cannot find module 'ajv'"); - }); - - jest.doMock('ajv-formats', () => { - throw new Error("Cannot find module 'ajv-formats'"); - }); - - // Attempting to import ajv-provider should fail - await expect(import('./ajv-provider.js')).rejects.toThrow(); - }); - - it('should be able to import cfworker-provider when ajv is missing', async () => { - // Mock ajv as not installed - jest.doMock('ajv', () => { - throw new Error("Cannot find module 'ajv'"); - }); - - jest.doMock('ajv-formats', () => { - throw new Error("Cannot find module 'ajv-formats'"); - }); - - // But cfworker-provider should import successfully - const cfworkerModule = await import('./cfworker-provider.js'); - expect(cfworkerModule.CfWorkerJsonSchemaValidator).toBeDefined(); - - // And should work correctly - const validator = new cfworkerModule.CfWorkerJsonSchemaValidator(); - const schema: JsonSchemaType = { type: 'string' }; - const validatorFn = validator.getValidator(schema); - expect(validatorFn('test').valid).toBe(true); - }); - }); - - describe('CfWorker not installed but AJV is', () => { - beforeEach(() => { - jest.resetModules(); - }); - - afterEach(() => { - jest.unmock('@cfworker/json-schema'); - }); - - it('should throw error when trying to import cfworker-provider without @cfworker/json-schema', async () => { - // Mock @cfworker/json-schema as not installed - jest.doMock('@cfworker/json-schema', () => { - throw new Error("Cannot find module '@cfworker/json-schema'"); - }); - - // Attempting to import cfworker-provider should fail - await expect(import('./cfworker-provider.js')).rejects.toThrow(); - }); - - it('should be able to import ajv-provider when @cfworker/json-schema is missing', async () => { - // Mock @cfworker/json-schema as not installed - jest.doMock('@cfworker/json-schema', () => { - throw new Error("Cannot find module '@cfworker/json-schema'"); - }); - - // But ajv-provider should import successfully - const ajvModule = await import('./ajv-provider.js'); - expect(ajvModule.AjvJsonSchemaValidator).toBeDefined(); - - // And should work correctly - const validator = new ajvModule.AjvJsonSchemaValidator(); - const schema: JsonSchemaType = { type: 'string' }; - const validatorFn = validator.getValidator(schema); - expect(validatorFn('test').valid).toBe(true); - }); - - it('should document that @cfworker/json-schema is required', () => { - const cfworkerProviderPath = join(__dirname, 'cfworker-provider.ts'); - const content = readFileSync(cfworkerProviderPath, 'utf-8'); - - expect(content).toContain('@cfworker/json-schema'); - }); - }); -}); diff --git a/typescript-sdk/tsconfig.cjs.json b/typescript-sdk/tsconfig.cjs.json deleted file mode 100644 index 3b46f11..0000000 --- a/typescript-sdk/tsconfig.cjs.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "module": "commonjs", - "moduleResolution": "node", - "outDir": "./dist/cjs" - }, - "exclude": ["**/*.test.ts", "src/__mocks__/**/*"] -} diff --git a/typescript-sdk/tsconfig.json b/typescript-sdk/tsconfig.json deleted file mode 100644 index 4cc22bf..0000000 --- a/typescript-sdk/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "target": "es2018", - "module": "Node16", - "moduleResolution": "Node16", - "declaration": true, - "declarationMap": true, - "sourceMap": true, - "outDir": "./dist", - "strict": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, - "resolveJsonModule": true, - "isolatedModules": true, - "skipLibCheck": true, - "baseUrl": ".", - "paths": { - "pkce-challenge": ["node_modules/pkce-challenge/dist/index.node"] - } - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "dist"] -} diff --git a/typescript-sdk/tsconfig.prod.json b/typescript-sdk/tsconfig.prod.json deleted file mode 100644 index 8fc00fc..0000000 --- a/typescript-sdk/tsconfig.prod.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "outDir": "./dist/esm" - }, - "exclude": ["**/*.test.ts", "src/__mocks__/**/*"] -}