typescript-sdk
modelcontextprotocol/typescript-sdk
- Type
- MCP server
- Scanned
- Nov 18, 2026
- Version
- 919bb8ea88b6
- Files read
- 1251
This is the official TypeScript toolkit for building, connecting, and upgrading clients and servers that use the Model Context Protocol (MCP). The biggest risk is a flaw in optional default-value handling that could let a malicious server tamper with your app's internal objects and potentially run code on your machine, alongside a server helper that listens on all network connections instead of staying local to your computer.
What it can reach
- Network
- Connects to remote MCP servers and OAuth login endpoints, accepts incoming web connections when hosting MCP servers, and downloads packages from npm during the upgrade skill workflow.
- Shell commands
- Starts local programs to communicate with MCP servers, and includes an upgrade skill that tells AI coding agents to run terminal commands like npx, grep, formatters, and tests.
- Files
- Reads local skill folders and markdown files from disk, and rewrites TypeScript, JavaScript, and package.json files in place when running the code upgrade tool.
- Secrets
- Handles and sends OAuth login tokens, refresh tokens, client secrets, and cryptographic signing keys, while limiting which environment variables are passed to local server processes.
Findings
-
MediumPrototype pollution in client elicitation applyDefaults via unvalidated anyOf/oneOf schemas
packages/client/src/client/client.ts:132
When a client enables capabilities.elicitation.form.applyDefaults, incoming elicitation/create requests (including embedded input_required requests auto-dispatched on 2026-07-28 connections) validate requestedSchema with ElicitRequestFormParamsSchema, which uses .catchall(z.unknown()). A malicious MCP server can attach an unvalidated anyOf or oneOf subschema containing a JSON-parsed own property named __proto__. When the user or handler accepts the elicitation, applyElicitationDefaults reads obj['__proto__'] (which resolves to Object.prototype on the result content object), sees it is not undefined, recurses into applyElicitationDefaults(propSchema, Object.prototype), and writes arbitrary attacker-chosen default properties onto Object.prototype. In Node.js MCP hosts that later spawn child processes (such as StdioClientTransport, where Node's child_process enumerates Object.prototype via for..in on env), polluting keys like NODE_OPTIONS can lead to arbitrary code execution.
Fix: Skip dangerous keys (__proto__, constructor, prototype) and check Object.prototype.hasOwnProperty.call(obj, key) before recursing in applyElicitationDefaults, and remove .catchall(z.unknown()) or strip composition keywords from ElicitRequestFormParamsSchema.
-
MediumcreateMcpExpressApp documents a 127.0.0.1 bind default but leaves app.listen bound to all interfaces
packages/middleware/express/src/express.ts:81
CreateMcpExpressAppOptions.host is documented as 'The hostname to bind to. Defaults to 127.0.0.1.' and the package README states that createMcpExpressApp() defaults the host to 127.0.0.1. In reality, createMcpExpressApp only uses the host option to decide whether to install Host and Origin header validation middleware and never binds or overrides app.listen. When a developer calls app.listen(port) on the returned Express app without repeating '127.0.0.1', Node.js binds to 0.0.0.0 / :: (all network interfaces). Because Host and Origin middleware only inspect HTTP headers, any attacker on the local network can reach the server by sending Host: 127.0.0.1 with no Origin header.
Fix: Override app.listen on the Express instance returned by createMcpExpressApp so calls that omit a hostname pass the configured host ('127.0.0.1' by default) to the underlying HTTP server, or clearly document that callers must still pass '127.0.0.1' to app.listen(port, '127.0.0.1').
-
LowClient transports leak requestInit headers across origins during OAuth flows
packages/client/src/client/streamableHttp.ts:399
StreamableHTTPClientTransport and SSEClientTransport document placing static fallback Authorization headers or custom server headers in requestInit.headers alongside an authProvider. However, both transports build _fetchWithInit with createFetchWithInit(opts?.fetch, opts?.requestInit) and pass it as fetchFn to onUnauthorized, auth, and finishAuth. When a server returns HTTP 401 with a cross-origin resource_metadata URL in WWW-Authenticate or advertises an external authorization_servers URL, _fetchWithInit sends all of requestInit.headers (including static Authorization tokens, API keys, or cookies meant only for the MCP server) to those cross-origin endpoints. In addition, createFetchWithInit merges headers via plain-object spread without case normalization, so a capitalized Authorization entry in requestInit.headers is concatenated with lowercase authorization headers on client_secret_basic token requests.
Fix: Do not forward server-specific requestInit.headers (especially Authorization and Cookie) to cross-origin OAuth discovery, registration, or token endpoints, and merge headers using the Fetch Headers class so header names are matched case-insensitively.
-
LowMissing HTTPS and loopback/private-network restrictions on OAuth discovery and registration URLs
packages/client/src/client/auth.ts:1780
When handling a 401/403 challenge or OAuth discovery from a remote MCP server, the client accepts arbitrary URLs in the WWW-Authenticate resource_metadata parameter and fetches them directly without checking for HTTPS or blocking loopback, link-local, or private network addresses. Likewise, authorization_servers and registration_endpoint only use SafeUrlSchema (which blocks javascript:, data:, and vbscript:, but permits plain http:// and internal IPs), and registerClient POSTs to registrationUrl without calling assertSecureTokenEndpoint while echoing the raw response body in RegistrationRejectedError. Even assertSecureTokenEndpoint exempts localhost and 127.0.0.1 unconditionally when the MCP server itself is remote. In cloud gateways or developer machines connecting to untrusted MCP servers, this allows server-side request forgery (GET and POST) against internal or localhost services.
Fix: Require https: on resource_metadata, authorization_servers, and registration_endpoint (matching assertSecureTokenEndpoint), and only allow the loopback HTTP exemption when the MCP server URL itself targets a loopback host.
-
LowURL-mode elicitation schema permits javascript:, data:, and file: URLs
packages/core/src/schemas.ts:2012
ElicitRequestURLParamsSchema (and its frozen 2025-11-25 and 2026-07-28 wire copies) validates the server-supplied navigation URL with z.string().url() rather than SafeUrlSchema, and UrlElicitationRequiredError (-32042) casts error.data.elicitations without validating URLs at all. Unlike SafeUrlSchema in auth.ts, z.string().url() accepts javascript:, data:, vbscript:, and file: schemes. If a client or host relies on the SDK's elicitation validation and passes params.url to window.open or an OS URL launcher (such as Electron shell.openExternal), a malicious MCP server can trigger script execution or launch local files.
Fix: Restrict ElicitRequestURLParamsSchema (in core and both wire codecs) to https: (and http: only where appropriate) or apply SafeUrlSchema while also blocking file:, and validate elicitations inside ProtocolError.fromError for UrlElicitationRequiredError.
-
LowCatastrophic regex backtracking (ReDoS) in UriTemplate.match on multi-wildcard templates
packages/core-internal/src/shared/uriTemplate.ts:235
UriTemplate.partToRegExp compiles {+var} and {#var} expressions into greedy (.+) capture groups and allows input URIs up to MAX_TEMPLATE_LENGTH (1,000,000 characters). If a server registers a ResourceTemplate containing multiple {+...} or {#...} expressions (for example, file://{+dir}/{+name}.txt), McpServer runs uriTemplate.match() on every resources/read request—including inside resolveScopeChallenge before OAuth scope enforcement. A single request with tens or hundreds of thousands of repeated '/' characters causes quadratic or cubic backtracking in V8's regex engine and blocks the event loop.
Fix: Lower MAX_TEMPLATE_LENGTH for incoming resource URIs to a reasonable bound (such as 8,192 characters), precompile the regex once in the UriTemplate constructor, and avoid unbounded greedy (.+) patterns across repeated delimiters.
-
LowUnescaped error message in server-legacy WWW-Authenticate header
packages/server-legacy/src/auth/middleware/bearerAuth.ts:68
Unlike the updated buildWwwAuthenticateHeader helper in @modelcontextprotocol/server (which escapes quotes and backslashes and strips non-printable characters), requireBearerAuth in @modelcontextprotocol/server-legacy interpolates error.message directly into the WWW-Authenticate Bearer header. If a custom token verifier includes untrusted input or double quotes in an InvalidTokenError or InsufficientScopeError message, it can inject extra WWW-Authenticate parameters (such as resource_metadata or scope) or cause res.set to throw on invalid header characters and return a 500 error.
Fix: Escape backslashes and double quotes and strip control/non-ASCII characters when formatting WWW-Authenticate parameter values, matching buildWwwAuthenticateHeader in @modelcontextprotocol/server.
-
LowExample HTTP servers and Express guide omit 127.0.0.1 bind address and listen on all interfaces
Several runnable example servers (including hono/server.ts, bearer-auth-web/server.ts, legacy-routing/server.ts, repl/server.ts, sse-polling/server.ts, and standalone-get/server.ts) as well as docs/serving/express.md call serve() or listen() with only a port while logging or stating that they bind to 127.0.0.1. In Node.js and @hono/node-server, omitting the hostname binds to 0.0.0.0 / ::, allowing non-browser attackers on the local network to reach the server and bypass Host header validation by sending Host: 127.0.0.1.
Fix: Pass hostname: '127.0.0.1' to serve() and '127.0.0.1' as the host argument to listen() in all localhost example servers and Express guide snippets.
-
LowInteractive OAuth client example omits OAuth state CSRF verification
examples/oauth/simpleOAuthClient.ts:157
The SDK's finishAuth() method leaves OAuth state parameter verification to the caller, as noted in the OAuth client guide. However, simpleOAuthClient.ts and InMemoryOAuthClientProvider never generate or check a state parameter on the local callback listener (127.0.0.1:8090) before exchanging the authorization code, exposing users who run or copy this example to OAuth login CSRF.
Fix: Generate a random state nonce in InMemoryOAuthClientProvider.state() and verify that callbackParams.get('state') matches it before calling transport.finishAuth(callbackParams).
