@draht/mcp 2026.11.27 → 2026.12.3-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.d.ts +105 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +318 -33
- package/dist/client.js.map +1 -1
- package/dist/config-schema.d.ts +109 -0
- package/dist/config-schema.d.ts.map +1 -0
- package/dist/config-schema.js +105 -0
- package/dist/config-schema.js.map +1 -0
- package/dist/config.d.ts +6 -74
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +9 -2
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/oauth/callback.d.ts.map +1 -1
- package/dist/oauth/callback.js +4 -2
- package/dist/oauth/callback.js.map +1 -1
- package/dist/protocol/http-headers.d.ts +31 -0
- package/dist/protocol/http-headers.d.ts.map +1 -0
- package/dist/protocol/http-headers.js +129 -0
- package/dist/protocol/http-headers.js.map +1 -0
- package/dist/protocol/stateless.d.ts +47 -0
- package/dist/protocol/stateless.d.ts.map +1 -0
- package/dist/protocol/stateless.js +102 -0
- package/dist/protocol/stateless.js.map +1 -0
- package/dist/protocol/types.d.ts +33 -0
- package/dist/protocol/types.d.ts.map +1 -1
- package/dist/protocol/types.js +5 -0
- package/dist/protocol/types.js.map +1 -1
- package/dist/transports/streamable-http.d.ts +14 -4
- package/dist/transports/streamable-http.d.ts.map +1 -1
- package/dist/transports/streamable-http.js +81 -26
- package/dist/transports/streamable-http.js.map +1 -1
- package/dist/transports/transport.d.ts +12 -0
- package/dist/transports/transport.d.ts.map +1 -1
- package/dist/transports/transport.js.map +1 -1
- package/package.json +8 -2
package/dist/config.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAIpF,YAAY,EACX,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,oBAAoB,GACpB,MAAM,oBAAoB,CAAC;AAE5B;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAC9B;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,oBAAoB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,GACzE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,mBAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,GACvE;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtC,qEAAqE;AACrE,MAAM,WAAW,sBAAsB;IACtC;;;;OAIG;IACH,6BAA6B,CAAC,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAAC;CACpF;AAID;;;GAGG;AACH,wBAAgB,uBAAuB,CACtC,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,OAAO,EACZ,OAAO,GAAE,sBAA2B,GAClC,qBAAqB,CAuBvB;AA+GD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAE3E"}
|
package/dist/config.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The `mcpServers` configuration shape that MCP clients share, so configurations can be copied between
|
|
3
3
|
* them: stdio servers (`command`, `args`, `env`, `cwd`), Streamable HTTP servers (`url`, `headers`,
|
|
4
|
-
* `oauth`), and `enabled`, `description` and `
|
|
4
|
+
* `oauth`), and `enabled`, `description`, `timeout` and `protocol` for both.
|
|
5
5
|
*
|
|
6
6
|
* ```json
|
|
7
7
|
* {
|
|
@@ -14,8 +14,12 @@
|
|
|
14
14
|
*
|
|
15
15
|
* Applications add fields of their own: {@link validateMcpServerConfig} keeps fields it does not know
|
|
16
16
|
* for the caller to check afterwards.
|
|
17
|
+
*
|
|
18
|
+
* The shape itself lives in `config-schema.ts`: a JSON Schema the configuration types derive from,
|
|
19
|
+
* whose parts applications compose into published schemas for their config files.
|
|
17
20
|
*/
|
|
18
21
|
import { parseClientMetadataBaseUrl } from "./oauth/client-metadata-base.js";
|
|
22
|
+
import { STATELESS_PROTOCOL_VERSION } from "./protocol/types.js";
|
|
19
23
|
const SERVER_NAME = /^[A-Za-z0-9_-]+$/;
|
|
20
24
|
/**
|
|
21
25
|
* Validate one entry of the `mcpServers` shape (configuration files are a trust boundary). Server
|
|
@@ -54,9 +58,12 @@ function isRecord(value) {
|
|
|
54
58
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
55
59
|
}
|
|
56
60
|
function validateBaseFields(entry) {
|
|
57
|
-
const { enabled, timeout, description } = entry;
|
|
61
|
+
const { enabled, timeout, description, protocol } = entry;
|
|
58
62
|
if (enabled !== undefined && typeof enabled !== "boolean")
|
|
59
63
|
return "enabled must be a boolean";
|
|
64
|
+
if (protocol !== undefined && protocol !== "auto" && protocol !== STATELESS_PROTOCOL_VERSION) {
|
|
65
|
+
return `protocol must be "auto" or "${STATELESS_PROTOCOL_VERSION}"`;
|
|
66
|
+
}
|
|
60
67
|
if (description !== undefined && typeof description !== "string")
|
|
61
68
|
return "description must be a string";
|
|
62
69
|
if (timeout !== undefined && (typeof timeout !== "number" || !(timeout > 0))) {
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,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B,MAAM,GAAG,GAAG,OAAO,WAAW,KAAK,QAAQ,IAAI,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5G,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,QAAQ,KAAK,OAAO,IAAI,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;YACjH,OAAO,6FAA6F,CAAC;QACtG,CAAC;IACF,CAAC;IACD,OAAO,qBAAqB,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,qBAAqB,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAChF,CAAC;AAED,0EAA0E;AAC1E,SAAS,qBAAqB,CAAC,KAAa;IAC3C,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACvC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3B,OAAO,GAAG,CAAC,QAAQ,KAAK,OAAO,IAAI,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,MAAM,KAAK,EAAE,IAAI,GAAG,CAAC,IAAI,KAAK,EAAE,CAAC;AAClH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAA8B;IACjE,OAAO,KAAK,CAAC,OAAO,KAAK,SAAS,IAAI,KAAK,CAAC,GAAG,KAAK,SAAS,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC;AAC3F,CAAC","sourcesContent":["/**\n * The `mcpServers` configuration shape that MCP clients share, so configurations can be copied between\n * them: stdio servers (`command`, `args`, `env`, `cwd`), Streamable HTTP servers (`url`, `headers`,\n * `oauth`), and `enabled`, `description` and `timeout` for both.\n *\n * ```json\n * {\n * \"mcpServers\": {\n * \"filesystem\": { \"command\": \"npx\", \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \".\"] },\n * \"docs\": { \"url\": \"https://example.com/mcp\", \"headers\": { \"Authorization\": \"Bearer ${DOCS_TOKEN}\" } }\n * }\n * }\n * ```\n *\n * Applications add fields of their own: {@link validateMcpServerConfig} keeps fields it does not know\n * for the caller to check afterwards.\n */\n\nimport { parseClientMetadataBaseUrl } from \"./oauth/client-metadata-base.ts\";\n\n/** Fields every server entry may have. */\ninterface McpServerConfigBase {\n\t/** What the server offers, in a sentence. */\n\tdescription?: string;\n\t/** Set to false to keep the entry without connecting. Default: true. */\n\tenabled?: boolean;\n\t/** Per-request timeout in seconds. */\n\ttimeout?: number;\n}\n\n/** A server started as a local program that speaks MCP over stdin and stdout. */\nexport interface McpStdioServerConfig extends McpServerConfigBase {\n\ttype?: \"stdio\";\n\tcommand: string;\n\targs?: string[];\n\t/** Added to the environment. The application decides whether values may reference variables (`${NAME}`). */\n\tenv?: Record<string, string>;\n\t/** The application decides what relative paths resolve against. */\n\tcwd?: string;\n}\n\n/** OAuth client settings for servers that do not support dynamic client registration. */\nexport interface McpOAuthConfig {\n\t/** Pre-registered client id. Without it, the application registers a client with the authorization server. */\n\tclientId?: string;\n\t/** As configured; the application decides whether it may reference variables. */\n\tclientSecret?: string;\n\t/**\n\t * Port of the loopback callback server, for clients registered with a fixed redirect URI. Without\n\t * `callbackUrl`, the redirect URI is `http://127.0.0.1:<port>/callback`.\n\t */\n\tcallbackPort?: number;\n\t/**\n\t * Redirect URI registered for `clientId`, for example `http://localhost:8080/oauth/callback`. It must\n\t * be an `http` URI on `localhost`, `127.0.0.1`, or `[::1]`. Without a port, the callback server\n\t * listens on `callbackPort` or a free port, which is added to the URI (RFC 8252).\n\t */\n\tcallbackUrl?: string;\n\t/** Scopes to request, separated by spaces. Default: the scopes the server advertises. */\n\tscope?: string;\n\t/** `client_name` sent with dynamic client registration. Default: the application's name. */\n\tclientName?: string;\n\t/**\n\t * How the application identifies itself without `clientId`. `dcr` (default): dynamic client\n\t * registration. `cimd`: the operator's Client ID Metadata Document under `clientMetadataBaseUrl`, and\n\t * sign-in fails when the authorization server does not support documents for public clients.\n\t *\n\t * draht: upstream's `auto` (the application's documents whenever the server supports them) is\n\t * rejected, so a document is only used when the operator configured one.\n\t */\n\tclientRegistration?: \"dcr\" | \"cimd\";\n\t/**\n\t * draht: required for `cimd` and rejected otherwise: an absolute https URL without userinfo, query, or\n\t * fragment that the operator hosts `client.json` and `<callback ID>/client.json` under. Validation\n\t * normalizes it to end in one `/`, keeping its path prefix. No default.\n\t */\n\tclientMetadataBaseUrl?: string;\n\t/**\n\t * Authorization server metadata document (RFC 8414 or OpenID Connect discovery) to use instead of\n\t * discovery through the server, for servers that advertise a wrong authorization server or none.\n\t * The document is trusted as configured. Must use https, except on loopback hosts.\n\t */\n\tauthServerMetadataUrl?: string;\n}\n\n/** A server reached over Streamable HTTP. */\nexport interface McpHttpServerConfig extends McpServerConfigBase {\n\ttype?: \"http\";\n\turl: string;\n\t/** Sent with every request. The application decides whether values may reference variables. */\n\theaders?: Record<string, string>;\n\toauth?: McpOAuthConfig;\n}\n\n/** One entry of the `mcpServers` shape: a stdio or a Streamable HTTP server. */\nexport type McpServerConfig = McpStdioServerConfig | McpHttpServerConfig;\n\n/**\n * A validated server entry, tagged with its transport, or why it is invalid. The config is the entry\n * as given: fields the validator does not know are kept, unchecked, for the caller to check. draht: with\n * `cimd`, the config is a copy whose `oauth.clientMetadataBaseUrl` is normalized.\n */\nexport type McpServerConfigResult =\n\t| { kind: \"stdio\"; config: McpStdioServerConfig & Record<string, unknown> }\n\t| { kind: \"http\"; config: McpHttpServerConfig & Record<string, unknown> }\n\t| { kind: \"invalid\"; error: string };\n\n/** What the application adds to the validation of server entries. */\nexport interface McpServerConfigOptions {\n\t/**\n\t * Checks the `oauth.callbackUrl` (undefined: none configured) of an entry with\n\t * `oauth.clientRegistration: \"cimd\"`: the operator's Client ID Metadata Documents must list it.\n\t * Returns an error message. Without this check, `\"cimd\"` is refused.\n\t */\n\tcheckMetadataDocumentCallback?(callbackUrl: string | undefined): string | undefined;\n}\n\nconst SERVER_NAME = /^[A-Za-z0-9_-]+$/;\n\n/**\n * Validate one entry of the `mcpServers` shape (configuration files are a trust boundary). Server\n * names are letters, digits, `_` and `-`, which tool names and namespaces are built from.\n */\nexport function validateMcpServerConfig(\n\tname: string,\n\traw: unknown,\n\toptions: McpServerConfigOptions = {},\n): McpServerConfigResult {\n\tconst invalid = (error: string): McpServerConfigResult => ({ kind: \"invalid\", error });\n\tif (!SERVER_NAME.test(name)) return invalid(`invalid server name \"${name}\" (use letters, digits, \"_\" and \"-\")`);\n\tif (!isRecord(raw)) return invalid(`server \"${name}\" must be an object`);\n\tconst fieldsError = validateBaseFields(raw);\n\tif (fieldsError) return invalid(`server \"${name}\": ${fieldsError}`);\n\tconst { type, url, command } = raw;\n\tif (type === \"sse\") {\n\t\treturn invalid(`server \"${name}\": legacy SSE transport is not supported; use the streamable HTTP URL`);\n\t}\n\t// The casts below hold because the fields were checked one by one, which the types cannot express.\n\tif (typeof url === \"string\" && (type === undefined || type === \"http\" || type === \"streamable-http\")) {\n\t\tconst oauth = validateHttpFields(raw, url, options);\n\t\tif (typeof oauth === \"string\") return invalid(`server \"${name}\": ${oauth}`);\n\t\tconst config = oauth ? { ...raw, oauth } : raw;\n\t\treturn { kind: \"http\", config: config as McpHttpServerConfig & Record<string, unknown> };\n\t}\n\tif (typeof command === \"string\" && (type === undefined || type === \"stdio\")) {\n\t\tconst error = validateStdioFields(raw);\n\t\tif (error) return invalid(`server \"${name}\": ${error}`);\n\t\treturn { kind: \"stdio\", config: raw as McpStdioServerConfig & Record<string, unknown> };\n\t}\n\treturn invalid(`server \"${name}\" needs either \"command\" (stdio) or \"url\" (streamable HTTP)`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction validateBaseFields(entry: Record<string, unknown>): string | undefined {\n\tconst { enabled, timeout, description } = entry;\n\tif (enabled !== undefined && typeof enabled !== \"boolean\") return \"enabled must be a boolean\";\n\tif (description !== undefined && typeof description !== \"string\") return \"description must be a string\";\n\tif (timeout !== undefined && (typeof timeout !== \"number\" || !(timeout > 0))) {\n\t\treturn \"timeout must be a positive number of seconds\";\n\t}\n\treturn undefined;\n}\n\n/** An error message, or the `oauth` object to put in the config when validation normalized it. */\nfunction validateHttpFields(\n\tentry: Record<string, unknown>,\n\turl: string,\n\toptions: McpServerConfigOptions,\n): string | Record<string, unknown> | undefined {\n\tif (!URL.canParse(url) || !/^https?:$/.test(new URL(url).protocol)) return \"url must be an http or https URL\";\n\tif (entry.headers !== undefined && !isStringRecord(entry.headers)) return \"headers must map names to strings\";\n\treturn validateOAuth(entry.oauth, options);\n}\n\nfunction validateStdioFields(entry: Record<string, unknown>): string | undefined {\n\tconst { args, env, cwd } = entry;\n\tif (args !== undefined && !(Array.isArray(args) && args.every((arg) => typeof arg === \"string\"))) {\n\t\treturn \"args must be an array of strings\";\n\t}\n\tif (env !== undefined && !isStringRecord(env)) return \"env must map names to strings\";\n\tif (cwd !== undefined && typeof cwd !== \"string\") return \"cwd must be a string\";\n\treturn undefined;\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n\treturn isRecord(value) && Object.values(value).every((entry) => typeof entry === \"string\");\n}\n\nconst LOOPBACK_HOSTS = [\"localhost\", \"127.0.0.1\", \"[::1]\"];\n\n/** An error message, a copy of `value` with a normalized `clientMetadataBaseUrl`, or `undefined` when valid as is. */\nfunction validateOAuth(value: unknown, options: McpServerConfigOptions): string | Record<string, unknown> | undefined {\n\tif (value === undefined) return undefined;\n\tif (!isRecord(value)) return \"oauth must be an object\";\n\tif (value.clientId !== undefined && typeof value.clientId !== \"string\") return \"oauth.clientId must be a string\";\n\tif (value.clientSecret !== undefined && typeof value.clientSecret !== \"string\") {\n\t\treturn \"oauth.clientSecret must be a string\";\n\t}\n\tconst port = value.callbackPort;\n\tif (port !== undefined && (typeof port !== \"number\" || !Number.isInteger(port) || port < 1 || port > 65535)) {\n\t\treturn \"oauth.callbackPort must be a port number\";\n\t}\n\tif (value.callbackUrl !== undefined) {\n\t\tif (typeof value.callbackUrl !== \"string\" || !isLoopbackRedirectUri(value.callbackUrl)) {\n\t\t\treturn \"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment\";\n\t\t}\n\t\tconst urlPort = new URL(value.callbackUrl).port;\n\t\tif (urlPort && port !== undefined && Number(urlPort) !== port) {\n\t\t\treturn \"oauth.callbackUrl and oauth.callbackPort name different ports\";\n\t\t}\n\t}\n\tif (value.scope !== undefined && typeof value.scope !== \"string\") return \"oauth.scope must be a string\";\n\tif (value.clientName !== undefined && (typeof value.clientName !== \"string\" || !value.clientName.trim())) {\n\t\treturn \"oauth.clientName must be a non-empty string\";\n\t}\n\t// draht: no `auto`. `cimd` is the operator's opt-in and a public client, so it takes no client id, name,\n\t// or secret, and it needs the operator's base; a base without `cimd` is a configuration mistake.\n\tconst registration = value.clientRegistration;\n\tlet clientMetadataBaseUrl: string | undefined;\n\tif (registration !== undefined && registration !== \"dcr\") {\n\t\tif (registration !== \"cimd\") return 'oauth.clientRegistration must be \"dcr\" or \"cimd\"';\n\t\tif (value.clientId !== undefined || value.clientName !== undefined || value.clientSecret !== undefined) {\n\t\t\treturn 'oauth.clientRegistration \"cimd\" cannot be combined with oauth.clientId, oauth.clientName, or oauth.clientSecret';\n\t\t}\n\t\tif (!options.checkMetadataDocumentCallback) {\n\t\t\treturn 'oauth.clientRegistration \"cimd\" is not supported: there are no Client ID Metadata Documents';\n\t\t}\n\t\tconst callbackError = options.checkMetadataDocumentCallback(\n\t\t\ttypeof value.callbackUrl === \"string\" ? value.callbackUrl : undefined,\n\t\t);\n\t\tif (callbackError) return callbackError;\n\t\tclientMetadataBaseUrl = parseClientMetadataBaseUrl(value.clientMetadataBaseUrl);\n\t\tif (!clientMetadataBaseUrl) {\n\t\t\treturn 'oauth.clientMetadataBaseUrl is required for \"cimd\" and must be an absolute HTTPS URL without userinfo, query, or fragment';\n\t\t}\n\t} else if (value.clientMetadataBaseUrl !== undefined) {\n\t\treturn 'oauth.clientMetadataBaseUrl requires oauth.clientRegistration \"cimd\"';\n\t}\n\tconst metadataUrl = value.authServerMetadataUrl;\n\tif (metadataUrl !== undefined) {\n\t\tconst url = typeof metadataUrl === \"string\" && URL.canParse(metadataUrl) ? new URL(metadataUrl) : undefined;\n\t\tif (!url || !(url.protocol === \"https:\" || (url.protocol === \"http:\" && LOOPBACK_HOSTS.includes(url.hostname)))) {\n\t\t\treturn \"oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]\";\n\t\t}\n\t}\n\treturn clientMetadataBaseUrl ? { ...value, clientMetadataBaseUrl } : undefined;\n}\n\n/** Whether a redirect URI can be served by a loopback callback server. */\nfunction isLoopbackRedirectUri(value: string): boolean {\n\tif (!URL.canParse(value)) return false;\n\tconst url = new URL(value);\n\treturn url.protocol === \"http:\" && LOOPBACK_HOSTS.includes(url.hostname) && url.search === \"\" && url.hash === \"\";\n}\n\n/**\n * Whether an entry overrides a server defined elsewhere instead of defining one: it has no `command`,\n * `url` or `type`. Applications let a less trusted file (a project's) override a few fields, such as\n * `enabled`, of a server a trusted file defines; which fields is theirs to decide.\n */\nexport function isMcpServerOverride(entry: Record<string, unknown>): boolean {\n\treturn entry.command === undefined && entry.url === undefined && entry.type === undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAGH,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AA6BjE,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAEvC;;;GA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: stdio servers (`command`, `args`, `env`, `cwd`), Streamable HTTP servers (`url`, `headers`,\n * `oauth`), and `enabled`, `description`, `timeout` and `protocol` for both.\n *\n * ```json\n * {\n * \"mcpServers\": {\n * \"filesystem\": { \"command\": \"npx\", \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \".\"] },\n * \"docs\": { \"url\": \"https://example.com/mcp\", \"headers\": { \"Authorization\": \"Bearer ${DOCS_TOKEN}\" } }\n * }\n * }\n * ```\n *\n * Applications add fields of their own: {@link validateMcpServerConfig} keeps fields it does not know\n * for the caller to check afterwards.\n *\n * The shape itself lives in `config-schema.ts`: a JSON Schema the configuration types derive from,\n * whose parts applications compose into published schemas for their config files.\n */\n\nimport type { McpHttpServerConfig, McpStdioServerConfig } from \"./config-schema.ts\";\nimport { parseClientMetadataBaseUrl } from \"./oauth/client-metadata-base.ts\";\nimport { STATELESS_PROTOCOL_VERSION } from \"./protocol/types.ts\";\n\nexport type {\n\tMcpHttpServerConfig,\n\tMcpOAuthConfig,\n\tMcpServerConfig,\n\tMcpStdioServerConfig,\n} from \"./config-schema.ts\";\n\n/**\n * A validated server entry, tagged with its transport, or why it is invalid. The config is the entry\n * as given: fields the validator does not know are kept, unchecked, for the caller to check. draht: with\n * `cimd`, the config is a copy whose `oauth.clientMetadataBaseUrl` is normalized.\n */\nexport type McpServerConfigResult =\n\t| { kind: \"stdio\"; config: McpStdioServerConfig & Record<string, unknown> }\n\t| { kind: \"http\"; config: McpHttpServerConfig & Record<string, unknown> }\n\t| { kind: \"invalid\"; error: string };\n\n/** What the application adds to the validation of server entries. */\nexport interface McpServerConfigOptions {\n\t/**\n\t * Checks the `oauth.callbackUrl` (undefined: none configured) of an entry with\n\t * `oauth.clientRegistration: \"cimd\"`: the operator's Client ID Metadata Documents must list it.\n\t * Returns an error message. Without this check, `\"cimd\"` is refused.\n\t */\n\tcheckMetadataDocumentCallback?(callbackUrl: string | undefined): string | undefined;\n}\n\nconst SERVER_NAME = /^[A-Za-z0-9_-]+$/;\n\n/**\n * Validate one entry of the `mcpServers` shape (configuration files are a trust boundary). Server\n * names are letters, digits, `_` and `-`, which tool names and namespaces are built from.\n */\nexport function validateMcpServerConfig(\n\tname: string,\n\traw: unknown,\n\toptions: McpServerConfigOptions = {},\n): McpServerConfigResult {\n\tconst invalid = (error: string): McpServerConfigResult => ({ kind: \"invalid\", error });\n\tif (!SERVER_NAME.test(name)) return invalid(`invalid server name \"${name}\" (use letters, digits, \"_\" and \"-\")`);\n\tif (!isRecord(raw)) return invalid(`server \"${name}\" must be an object`);\n\tconst fieldsError = validateBaseFields(raw);\n\tif (fieldsError) return invalid(`server \"${name}\": ${fieldsError}`);\n\tconst { type, url, command } = raw;\n\tif (type === \"sse\") {\n\t\treturn invalid(`server \"${name}\": legacy SSE transport is not supported; use the streamable HTTP URL`);\n\t}\n\t// The casts below hold because the fields were checked one by one, which the types cannot express.\n\tif (typeof url === \"string\" && (type === undefined || type === \"http\" || type === \"streamable-http\")) {\n\t\tconst oauth = validateHttpFields(raw, url, options);\n\t\tif (typeof oauth === \"string\") return invalid(`server \"${name}\": ${oauth}`);\n\t\tconst config = oauth ? { ...raw, oauth } : raw;\n\t\treturn { kind: \"http\", config: config as McpHttpServerConfig & Record<string, unknown> };\n\t}\n\tif (typeof command === \"string\" && (type === undefined || type === \"stdio\")) {\n\t\tconst error = validateStdioFields(raw);\n\t\tif (error) return invalid(`server \"${name}\": ${error}`);\n\t\treturn { kind: \"stdio\", config: raw as McpStdioServerConfig & Record<string, unknown> };\n\t}\n\treturn invalid(`server \"${name}\" needs either \"command\" (stdio) or \"url\" (streamable HTTP)`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction validateBaseFields(entry: Record<string, unknown>): string | undefined {\n\tconst { enabled, timeout, description, protocol } = entry;\n\tif (enabled !== undefined && typeof enabled !== \"boolean\") return \"enabled must be a boolean\";\n\tif (protocol !== undefined && protocol !== \"auto\" && protocol !== STATELESS_PROTOCOL_VERSION) {\n\t\treturn `protocol must be \"auto\" or \"${STATELESS_PROTOCOL_VERSION}\"`;\n\t}\n\tif (description !== undefined && typeof description !== \"string\") return \"description must be a string\";\n\tif (timeout !== undefined && (typeof timeout !== \"number\" || !(timeout > 0))) {\n\t\treturn \"timeout must be a positive number of seconds\";\n\t}\n\treturn undefined;\n}\n\n/** An error message, or the `oauth` object to put in the config when validation normalized it. */\nfunction validateHttpFields(\n\tentry: Record<string, unknown>,\n\turl: string,\n\toptions: McpServerConfigOptions,\n): string | Record<string, unknown> | undefined {\n\tif (!URL.canParse(url) || !/^https?:$/.test(new URL(url).protocol)) return \"url must be an http or https URL\";\n\tif (entry.headers !== undefined && !isStringRecord(entry.headers)) return \"headers must map names to strings\";\n\treturn validateOAuth(entry.oauth, options);\n}\n\nfunction validateStdioFields(entry: Record<string, unknown>): string | undefined {\n\tconst { args, env, cwd } = entry;\n\tif (args !== undefined && !(Array.isArray(args) && args.every((arg) => typeof arg === \"string\"))) {\n\t\treturn \"args must be an array of strings\";\n\t}\n\tif (env !== undefined && !isStringRecord(env)) return \"env must map names to strings\";\n\tif (cwd !== undefined && typeof cwd !== \"string\") return \"cwd must be a string\";\n\treturn undefined;\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n\treturn isRecord(value) && Object.values(value).every((entry) => typeof entry === \"string\");\n}\n\nconst LOOPBACK_HOSTS = [\"localhost\", \"127.0.0.1\", \"[::1]\"];\n\n/** An error message, a copy of `value` with a normalized `clientMetadataBaseUrl`, or `undefined` when valid as is. */\nfunction validateOAuth(value: unknown, options: McpServerConfigOptions): string | Record<string, unknown> | undefined {\n\tif (value === undefined) return undefined;\n\tif (!isRecord(value)) return \"oauth must be an object\";\n\tif (value.clientId !== undefined && typeof value.clientId !== \"string\") return \"oauth.clientId must be a string\";\n\tif (value.clientSecret !== undefined && typeof value.clientSecret !== \"string\") {\n\t\treturn \"oauth.clientSecret must be a string\";\n\t}\n\tconst port = value.callbackPort;\n\tif (port !== undefined && (typeof port !== \"number\" || !Number.isInteger(port) || port < 1 || port > 65535)) {\n\t\treturn \"oauth.callbackPort must be a port number\";\n\t}\n\tif (value.callbackUrl !== undefined) {\n\t\tif (typeof value.callbackUrl !== \"string\" || !isLoopbackRedirectUri(value.callbackUrl)) {\n\t\t\treturn \"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment\";\n\t\t}\n\t\tconst urlPort = new URL(value.callbackUrl).port;\n\t\tif (urlPort && port !== undefined && Number(urlPort) !== port) {\n\t\t\treturn \"oauth.callbackUrl and oauth.callbackPort name different ports\";\n\t\t}\n\t}\n\tif (value.scope !== undefined && typeof value.scope !== \"string\") return \"oauth.scope must be a string\";\n\tif (value.clientName !== undefined && (typeof value.clientName !== \"string\" || !value.clientName.trim())) {\n\t\treturn \"oauth.clientName must be a non-empty string\";\n\t}\n\t// draht: no `auto`. `cimd` is the operator's opt-in and a public client, so it takes no client id, name,\n\t// or secret, and it needs the operator's base; a base without `cimd` is a configuration mistake.\n\tconst registration = value.clientRegistration;\n\tlet clientMetadataBaseUrl: string | undefined;\n\tif (registration !== undefined && registration !== \"dcr\") {\n\t\tif (registration !== \"cimd\") return 'oauth.clientRegistration must be \"dcr\" or \"cimd\"';\n\t\tif (value.clientId !== undefined || value.clientName !== undefined || value.clientSecret !== undefined) {\n\t\t\treturn 'oauth.clientRegistration \"cimd\" cannot be combined with oauth.clientId, oauth.clientName, or oauth.clientSecret';\n\t\t}\n\t\tif (!options.checkMetadataDocumentCallback) {\n\t\t\treturn 'oauth.clientRegistration \"cimd\" is not supported: there are no Client ID Metadata Documents';\n\t\t}\n\t\tconst callbackError = options.checkMetadataDocumentCallback(\n\t\t\ttypeof value.callbackUrl === \"string\" ? value.callbackUrl : undefined,\n\t\t);\n\t\tif (callbackError) return callbackError;\n\t\tclientMetadataBaseUrl = parseClientMetadataBaseUrl(value.clientMetadataBaseUrl);\n\t\tif (!clientMetadataBaseUrl) {\n\t\t\treturn 'oauth.clientMetadataBaseUrl is required for \"cimd\" and must be an absolute HTTPS URL without userinfo, query, or fragment';\n\t\t}\n\t} else if (value.clientMetadataBaseUrl !== undefined) {\n\t\treturn 'oauth.clientMetadataBaseUrl requires oauth.clientRegistration \"cimd\"';\n\t}\n\tconst metadataUrl = value.authServerMetadataUrl;\n\tif (metadataUrl !== undefined) {\n\t\tconst url = typeof metadataUrl === \"string\" && URL.canParse(metadataUrl) ? new URL(metadataUrl) : undefined;\n\t\tif (!url || !(url.protocol === \"https:\" || (url.protocol === \"http:\" && LOOPBACK_HOSTS.includes(url.hostname)))) {\n\t\t\treturn \"oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]\";\n\t\t}\n\t}\n\treturn clientMetadataBaseUrl ? { ...value, clientMetadataBaseUrl } : undefined;\n}\n\n/** Whether a redirect URI can be served by a loopback callback server. */\nfunction isLoopbackRedirectUri(value: string): boolean {\n\tif (!URL.canParse(value)) return false;\n\tconst url = new URL(value);\n\treturn url.protocol === \"http:\" && LOOPBACK_HOSTS.includes(url.hostname) && url.search === \"\" && url.hash === \"\";\n}\n\n/**\n * Whether an entry overrides a server defined elsewhere instead of defining one: it has no `command`,\n * `url` or `type`. Applications let a less trusted file (a project's) override a few fields, such as\n * `enabled`, of a server a trusted file defines; which fields is theirs to decide.\n */\nexport function isMcpServerOverride(entry: Record<string, unknown>): boolean {\n\treturn entry.command === undefined && entry.url === undefined && entry.type === undefined;\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type { AuthProvider, McpFetch, UnauthorizedContext } from "./auth-provider.ts";
|
|
2
|
-
export { McpClient, type McpClientOptions, type McpRequestOptions } from "./client.ts";
|
|
2
|
+
export { McpClient, type McpClientOptions, type McpExtensionResultHandler, McpInitializeRejectedError, type McpRequestOptions, type McpSubscription, } from "./client.ts";
|
|
3
3
|
export { isMcpServerOverride, type McpHttpServerConfig, type McpOAuthConfig, type McpServerConfig, type McpServerConfigOptions, type McpServerConfigResult, type McpStdioServerConfig, validateMcpServerConfig, } from "./config.ts";
|
|
4
4
|
export { normalizeMcpInputSchema } from "./input-schema.ts";
|
|
5
5
|
export { type McpModelContentOptions, toMcpModelContent } from "./model-content.ts";
|
|
@@ -7,7 +7,7 @@ export { createMcpToolName, mcpNamespace, mcpServerSummary } from "./naming.ts";
|
|
|
7
7
|
export { type LimitedMcpContent, limitMcpContent, MCP_OUTPUT_MAX_BYTES, type McpOutputSaver, } from "./output-limit.ts";
|
|
8
8
|
export { type AudioContent, type BlobResourceContents, type CallToolResult, type ContentAnnotations, type ContentBlock, type EmbeddedResourceContent, type ImageContent, type LlmContent, type ResourceLinkContent, type TextContent, type TextResourceContents, toLlmContent, } from "./protocol/content.ts";
|
|
9
9
|
export { isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, JSON_RPC_ERROR_CODES, type JsonRpcErrorObject, type JsonRpcErrorResponse, type JsonRpcId, type JsonRpcMessage, type JsonRpcNotification, type JsonRpcRequest, type JsonRpcResponse, type JsonRpcSuccessResponse, McpAbortError, McpConnectionClosedError, McpError, McpTimeoutError, parseJsonRpcMessage, } from "./protocol/jsonrpc.ts";
|
|
10
|
-
export { type CancelledNotification, type ClientCapabilities, type Implementation, type InitializeParams, type InitializeResult, LATEST_PROTOCOL_VERSION, type ListResourcesResult, type ListResourceTemplatesResult, type ListToolsResult, type ProgressNotification, type ReadResourceResult, type Resource, type ResourceTemplate, type Root, type ServerCapabilities, SUPPORTED_PROTOCOL_VERSIONS, type SupportedProtocolVersion, type Tool, type ToolAnnotations, type ToolExecution, } from "./protocol/types.ts";
|
|
10
|
+
export { type CancelledNotification, type ClientCapabilities, type Implementation, type InitializeParams, type InitializeResult, LATEST_PROTOCOL_VERSION, type ListResourcesResult, type ListResourceTemplatesResult, type ListToolsResult, type LoggingLevel, type McpProtocolMode, type ProgressNotification, type ReadResourceResult, type Resource, type ResourceTemplate, type Root, type ServerCapabilities, STATELESS_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, type SubscriptionFilter, type SupportedProtocolVersion, type Tool, type ToolAnnotations, type ToolExecution, } from "./protocol/types.ts";
|
|
11
11
|
export { createMcpResultSchema } from "./result-schema.ts";
|
|
12
12
|
export { type McpPipe, type McpPipeHandlers, PipeTransport, type PipeTransportOptions, } from "./transports/pipe.ts";
|
|
13
13
|
export { StdioTransport, type StdioTransportOptions } from "./transports/stdio.ts";
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,YAAY,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACtF,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,YAAY,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACtF,OAAO,EACN,SAAS,EACT,KAAK,gBAAgB,EACrB,KAAK,yBAAyB,EAC9B,0BAA0B,EAC1B,KAAK,iBAAiB,EACtB,KAAK,eAAe,GACpB,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,mBAAmB,EACnB,KAAK,mBAAmB,EACxB,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,uBAAuB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,KAAK,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACpF,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,EACN,KAAK,iBAAiB,EACtB,eA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pB,aAAa,EACb,KAAK,oBAAoB,GACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,cAAc,EAAE,KAAK,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACnF,OAAO,EACN,oBAAoB,EACpB,YAAY,EACZ,sBAAsB,EACtB,uBAAuB,EACvB,KAAK,8BAA8B,GACnC,MAAM,iCAAiC,CAAC;AACzC,YAAY,EACX,YAAY,EACZ,yBAAyB,EACzB,yBAAyB,EACzB,2BAA2B,EAC3B,uBAAuB,GACvB,MAAM,2BAA2B,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { McpClient } from "./client.js";
|
|
1
|
+
export { McpClient, McpInitializeRejectedError, } from "./client.js";
|
|
2
2
|
export { isMcpServerOverride, validateMcpServerConfig, } from "./config.js";
|
|
3
3
|
export { normalizeMcpInputSchema } from "./input-schema.js";
|
|
4
4
|
export { toMcpModelContent } from "./model-content.js";
|
|
@@ -6,7 +6,7 @@ export { createMcpToolName, mcpNamespace, mcpServerSummary } from "./naming.js";
|
|
|
6
6
|
export { limitMcpContent, MCP_OUTPUT_MAX_BYTES, } from "./output-limit.js";
|
|
7
7
|
export { toLlmContent, } from "./protocol/content.js";
|
|
8
8
|
export { isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, JSON_RPC_ERROR_CODES, McpAbortError, McpConnectionClosedError, McpError, McpTimeoutError, parseJsonRpcMessage, } from "./protocol/jsonrpc.js";
|
|
9
|
-
export { LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, } from "./protocol/types.js";
|
|
9
|
+
export { LATEST_PROTOCOL_VERSION, STATELESS_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, } from "./protocol/types.js";
|
|
10
10
|
export { createMcpResultSchema } from "./result-schema.js";
|
|
11
11
|
export { PipeTransport, } from "./transports/pipe.js";
|
|
12
12
|
export { StdioTransport } from "./transports/stdio.js";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACN,SAAS,EAGT,0BAA0B,GAG1B,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,mBAAmB,EAOnB,uBAAuB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAA+B,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACpF,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,EAEN,eAAe,EACf,oBAAoB,GAEpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAYN,YAAY,GACZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EASpB,aAAa,EACb,wBAAwB,EACxB,QAAQ,EACR,eAAe,EACf,mBAAmB,GACnB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAMN,uBAAuB,EAYvB,0BAA0B,EAC1B,2BAA2B,GAM3B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAGN,aAAa,GAEb,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,cAAc,EAA8B,MAAM,uBAAuB,CAAC;AACnF,OAAO,EACN,oBAAoB,EACpB,YAAY,EACZ,sBAAsB,EACtB,uBAAuB,GAEvB,MAAM,iCAAiC,CAAC","sourcesContent":["export type { AuthProvider, McpFetch, UnauthorizedContext } from \"./auth-provider.ts\";\nexport {\n\tMcpClient,\n\ttype McpClientOptions,\n\ttype McpExtensionResultHandler,\n\tMcpInitializeRejectedError,\n\ttype McpRequestOptions,\n\ttype McpSubscription,\n} from \"./client.ts\";\nexport {\n\tisMcpServerOverride,\n\ttype McpHttpServerConfig,\n\ttype McpOAuthConfig,\n\ttype McpServerConfig,\n\ttype McpServerConfigOptions,\n\ttype McpServerConfigResult,\n\ttype McpStdioServerConfig,\n\tvalidateMcpServerConfig,\n} from \"./config.ts\";\nexport { normalizeMcpInputSchema } from \"./input-schema.ts\";\nexport { type McpModelContentOptions, toMcpModelContent } from \"./model-content.ts\";\nexport { createMcpToolName, mcpNamespace, mcpServerSummary } from \"./naming.ts\";\nexport {\n\ttype LimitedMcpContent,\n\tlimitMcpContent,\n\tMCP_OUTPUT_MAX_BYTES,\n\ttype McpOutputSaver,\n} from \"./output-limit.ts\";\nexport {\n\ttype AudioContent,\n\ttype BlobResourceContents,\n\ttype CallToolResult,\n\ttype ContentAnnotations,\n\ttype ContentBlock,\n\ttype EmbeddedResourceContent,\n\ttype ImageContent,\n\ttype LlmContent,\n\ttype ResourceLinkContent,\n\ttype TextContent,\n\ttype TextResourceContents,\n\ttoLlmContent,\n} from \"./protocol/content.ts\";\nexport {\n\tisJsonRpcNotification,\n\tisJsonRpcRequest,\n\tisJsonRpcResponse,\n\tJSON_RPC_ERROR_CODES,\n\ttype JsonRpcErrorObject,\n\ttype JsonRpcErrorResponse,\n\ttype JsonRpcId,\n\ttype JsonRpcMessage,\n\ttype JsonRpcNotification,\n\ttype JsonRpcRequest,\n\ttype JsonRpcResponse,\n\ttype JsonRpcSuccessResponse,\n\tMcpAbortError,\n\tMcpConnectionClosedError,\n\tMcpError,\n\tMcpTimeoutError,\n\tparseJsonRpcMessage,\n} from \"./protocol/jsonrpc.ts\";\nexport {\n\ttype CancelledNotification,\n\ttype ClientCapabilities,\n\ttype Implementation,\n\ttype InitializeParams,\n\ttype InitializeResult,\n\tLATEST_PROTOCOL_VERSION,\n\ttype ListResourcesResult,\n\ttype ListResourceTemplatesResult,\n\ttype ListToolsResult,\n\ttype LoggingLevel,\n\ttype McpProtocolMode,\n\ttype ProgressNotification,\n\ttype ReadResourceResult,\n\ttype Resource,\n\ttype ResourceTemplate,\n\ttype Root,\n\ttype ServerCapabilities,\n\tSTATELESS_PROTOCOL_VERSION,\n\tSUPPORTED_PROTOCOL_VERSIONS,\n\ttype SubscriptionFilter,\n\ttype SupportedProtocolVersion,\n\ttype Tool,\n\ttype ToolAnnotations,\n\ttype ToolExecution,\n} from \"./protocol/types.ts\";\nexport { createMcpResultSchema } from \"./result-schema.ts\";\nexport {\n\ttype McpPipe,\n\ttype McpPipeHandlers,\n\tPipeTransport,\n\ttype PipeTransportOptions,\n} from \"./transports/pipe.ts\";\nexport { StdioTransport, type StdioTransportOptions } from \"./transports/stdio.ts\";\nexport {\n\tMcpAuthRequiredError,\n\tMcpHttpError,\n\tMcpSessionExpiredError,\n\tStreamableHttpTransport,\n\ttype StreamableHttpTransportOptions,\n} from \"./transports/streamable-http.ts\";\nexport type {\n\tMcpTransport,\n\tMcpTransportCloseListener,\n\tMcpTransportErrorListener,\n\tMcpTransportMessageListener,\n\tMcpTransportSendOptions,\n} from \"./transports/transport.ts\";\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"callback.d.ts","sourceRoot":"","sources":["../../src/oauth/callback.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,4DAA4D;AAC5D,MAAM,MAAM,iBAAiB,GAAG;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEhG,MAAM,WAAW,0BAA0B;IAC1C,kDAAkD;IAClD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;OAGG;IACH,YA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AM,CAAC;IACd;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,kGAAkG;IAClG,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,sEAAsE;IACtE,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,iBAAiB,KAAK,MAAM,CAAC;CACjD;AAOD,qBAAa,mBAAmB;IAC/B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,KAAK,CAAW;IACxB,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,UAAU,CAAoD;IACtE,OAAO,CAAC,OAAO,CAQX;IAEJ,OAAO,eAYN;IAED,OAAa,MAAM,CAAC,OAAO,GAAE,0BAA+B,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAyB1F;IAED;;;OAGG;IACH,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CASpE;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAe3B;IAED,OAAO,CAAC,KAAK;IASb,OAAO,CAAC,MAAM;CAiDd"}
|
package/dist/oauth/callback.js
CHANGED
|
@@ -61,8 +61,10 @@ export class OAuthCallbackServer {
|
|
|
61
61
|
const closed = new Promise((resolve, reject) => {
|
|
62
62
|
this.server.close((error) => (error ? reject(error) : resolve()));
|
|
63
63
|
});
|
|
64
|
-
//
|
|
65
|
-
//
|
|
64
|
+
// close() only stops accepting new connections and calls back once every connection has ended. A
|
|
65
|
+
// browser may keep a connection open that has not sent a request (a preconnect or a spare keep-alive
|
|
66
|
+
// socket), and Node does not count it as idle. Waiting for it can take minutes. The callback page has
|
|
67
|
+
// been sent by now, so drop them all.
|
|
66
68
|
this.server.closeAllConnections();
|
|
67
69
|
await closed;
|
|
68
70
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"callback.js","sourceRoot":"","sources":["../../src/oauth/callback.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAoC,MAAM,WAAW,CAAC;AA4B3E,SAAS,SAAS,CAAC,IAAuB;IACzC,IAAI,IAAI,CAAC,EAAE;QAAE,OAAO,oDAAoD,CAAC;IACzE,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC;AAC3E,CAAC;AAED,MAAM,OAAO,mBAAmB;IACtB,WAAW,CAAS;IACrB,MAAM,CAAS;IACf,KAAK,CAAW;IAChB,SAAS,CAAS;IAClB,UAAU,CAAoD;IAC9D,OAAO,GAAG,IAAI,GAAG,EAQtB,CAAC;IAEJ,YACC,MAAc,EACd,WAAmB,EACnB,KAAe,EACf,SAAiB,EACjB,UAA6D;QAE7D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC9B,CAAC;IAED,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,GAA+B,EAAE;QAC3D,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,WAAW,CAAC;QACzC,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,IAAI,CAAC;QAClD,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,WAAW,CAAC;QACzC,IAAI,QAAyC,CAAC;QAC9C,MAAM,MAAM,GAAG,YAAY,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,EA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,CAAC,IAAI,EAAE,CAAC;YACX,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC,CAAC;YAClF,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,4BAA4B,EAAE,CAAC,CAAC;YAChF,OAAO;QACR,CAAC;QACD,MAAM,GAAG,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACxC,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;QAC1D,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IACzC,CAAC;CACD","sourcesContent":["import { createServer, type Server, type ServerResponse } from \"node:http\";\n\nexport interface OAuthCallback {\n\tcode: string;\n\tstate: string;\n\tiss?: string;\n}\n\n/** Outcome shown on the browser page after the redirect. */\nexport type OAuthCallbackPage = { ok: true } | { ok: false; message: string; details?: string };\n\nexport interface OAuthCallbackServerOptions {\n\t/** Address to listen on. Default: `127.0.0.1`. */\n\thost?: string;\n\t/**\n\t * Host name in `redirectUrl`, for example `localhost` for a client registered with it while\n\t * listening on `127.0.0.1`. Default: `host`.\n\t */\n\tredirectHost?: string;\n\tport?: number;\n\tpath?: string;\n\t/** More paths that receive the callback, for example a server-specific path of a redirect URI. */\n\textraPaths?: string[];\n\ttimeoutMs?: number;\n\t/** Render the browser page as HTML. Default: a plain-text message. */\n\trenderPage?: (page: OAuthCallbackPage) => string;\n}\n\nfunction plainText(page: OAuthCallbackPage): string {\n\tif (page.ok) return \"Authorization complete. You may close this window.\";\n\treturn page.details ? `${page.message}\\n\\n${page.details}` : page.message;\n}\n\nexport class OAuthCallbackServer {\n\treadonly redirectUrl: string;\n\tprivate server: Server;\n\tprivate paths: string[];\n\tprivate timeoutMs: number;\n\tprivate renderPage: ((page: OAuthCallbackPage) => string) | undefined;\n\tprivate pending = new Map<\n\t\tstring,\n\t\t{\n\t\t\tresolve: (callback: OAuthCallback) => void;\n\t\t\treject: (error: Error) => void;\n\t\t\ttimer: ReturnType<typeof setTimeout>;\n\t\t\tpath: string | undefined;\n\t\t}\n\t>();\n\n\tprivate constructor(\n\t\tserver: Server,\n\t\tredirectUrl: string,\n\t\tpaths: string[],\n\t\ttimeoutMs: number,\n\t\trenderPage: ((page: OAuthCallbackPage) => string) | undefined,\n\t) {\n\t\tthis.server = server;\n\t\tthis.redirectUrl = redirectUrl;\n\t\tthis.paths = paths;\n\t\tthis.timeoutMs = timeoutMs;\n\t\tthis.renderPage = renderPage;\n\t}\n\n\tstatic async listen(options: OAuthCallbackServerOptions = {}): Promise<OAuthCallbackServer> {\n\t\tconst host = options.host ?? \"127.0.0.1\";\n\t\tconst redirectHost = options.redirectHost ?? host;\n\t\tconst path = options.path ?? \"/callback\";\n\t\tlet instance: OAuthCallbackServer | undefined;\n\t\tconst server = createServer((request, response) =>\n\t\t\tinstance?.handle(request.url ?? \"/\", request.headers.host, response),\n\t\t);\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tserver.once(\"error\", reject);\n\t\t\tserver.listen(options.port ?? 0, host, () => {\n\t\t\t\tserver.off(\"error\", reject);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t\tconst address = server.address();\n\t\tif (!address || typeof address === \"string\") throw new Error(\"OAuth callback server did not bind to TCP\");\n\t\tinstance = new OAuthCallbackServer(\n\t\t\tserver,\n\t\t\t`http://${redirectHost.includes(\":\") ? `[${redirectHost}]` : redirectHost}:${address.port}${path}`,\n\t\t\t[path, ...(options.extraPaths ?? [])],\n\t\t\toptions.timeoutMs ?? 5 * 60_000,\n\t\t\toptions.renderPage,\n\t\t);\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Wait for the authorization response with `state`. With `path`, a response on another path fails, so\n\t * a server-specific redirect URI can tell authorization servers apart (RFC 9700 section 4.4.2.2).\n\t */\n\twaitForCallback(state: string, path?: string): Promise<OAuthCallback> {\n\t\tif (this.pending.has(state)) throw new Error(\"OAuth state is already pending\");\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.pending.delete(state);\n\t\t\t\treject(new Error(\"OAuth callback timed out\"));\n\t\t\t}, this.timeoutMs);\n\t\t\tthis.pending.set(state, { resolve, reject, timer, path });\n\t\t});\n\t}\n\n\tasync close(): Promise<void> {\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tclearTimeout(pending.timer);\n\t\t\tpending.reject(new Error(\"OAuth callback server closed\"));\n\t\t}\n\t\tthis.pending.clear();\n\t\tconst closed = new Promise<void>((resolve, reject) => {\n\t\t\tthis.server.close((error) => (error ? reject(error) : resolve()));\n\t\t});\n\t\t// `close()` waits for every connection, and a browser may keep an unused one open (a preconnect or a\n\t\t// spare keep-alive socket) for minutes. Responses have been sent by now, so drop them.\n\t\tthis.server.closeAllConnections();\n\t\tawait closed;\n\t}\n\n\tprivate reply(response: ServerResponse, status: number, page: OAuthCallbackPage): void {\n\t\tif (this.renderPage) {\n\t\t\tresponse.writeHead(status, { \"content-type\": \"text/html; charset=utf-8\", \"cache-control\": \"no-store\" });\n\t\t\tresponse.end(this.renderPage(page));\n\t\t} else {\n\t\t\tresponse.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" }).end(plainText(page));\n\t\t}\n\t}\n\n\tprivate handle(rawUrl: string, host: string | undefined, response: ServerResponse): void {\n\t\tconst url = new URL(rawUrl, this.redirectUrl);\n\t\tconst redirect = new URL(this.redirectUrl);\n\t\tif (host !== redirect.host || url.origin !== redirect.origin) {\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Unexpected redirect origin\" });\n\t\t\treturn;\n\t\t}\n\t\tif (!this.paths.includes(url.pathname)) {\n\t\t\tthis.reply(response, 404, { ok: false, message: \"Not found\" });\n\t\t\treturn;\n\t\t}\n\t\tconst state = url.searchParams.get(\"state\");\n\t\tconst pending = state ? this.pending.get(state) : undefined;\n\t\tif (!state || !pending) {\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Invalid or expired OAuth state\" });\n\t\t\treturn;\n\t\t}\n\t\t// Everything above (Host, origin, unknown path, unknown state) fails without touching the pending\n\t\t// sign-in. From here on the state is consumed, by design also on the wrong one of this server's paths:\n\t\t// a valid state on another redirect URI means an authorization server mixed up the response (RFC 9700\n\t\t// section 4.4.2.2), so the sign-in fails instead of waiting for a second response with the same state.\n\t\tclearTimeout(pending.timer);\n\t\tthis.pending.delete(state);\n\t\tif (pending.path !== undefined && url.pathname !== pending.path) {\n\t\t\tpending.reject(new Error(\"The authorization response arrived on another redirect URI\"));\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Unexpected redirect URI\" });\n\t\t\treturn;\n\t\t}\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tif (error) {\n\t\t\tconst description = url.searchParams.get(\"error_description\") ?? error;\n\t\t\tpending.reject(new Error(description));\n\t\t\tthis.reply(response, 200, {\n\t\t\t\tok: false,\n\t\t\t\tmessage: \"Authorization failed. You may close this window.\",\n\t\t\t\tdetails: description,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tif (!code) {\n\t\t\tpending.reject(new Error(\"OAuth callback did not include an authorization code\"));\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Missing authorization code\" });\n\t\t\treturn;\n\t\t}\n\t\tconst iss = url.searchParams.get(\"iss\");\n\t\tpending.resolve({ code, state, ...(iss ? { iss } : {}) });\n\t\tthis.reply(response, 200, { ok: true });\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"callback.js","sourceRoot":"","sources":["../../src/oauth/callback.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAoC,MAAM,WAA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EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,4BAA4B,EAAE,CAAC,CAAC;YAChF,OAAO;QACR,CAAC;QACD,MAAM,GAAG,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACxC,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;QAC1D,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IACzC,CAAC;CACD","sourcesContent":["import { createServer, type Server, type ServerResponse } from \"node:http\";\n\nexport interface OAuthCallback {\n\tcode: string;\n\tstate: string;\n\tiss?: string;\n}\n\n/** Outcome shown on the browser page after the redirect. */\nexport type OAuthCallbackPage = { ok: true } | { ok: false; message: string; details?: string };\n\nexport interface OAuthCallbackServerOptions {\n\t/** Address to listen on. Default: `127.0.0.1`. */\n\thost?: string;\n\t/**\n\t * Host name in `redirectUrl`, for example `localhost` for a client registered with it while\n\t * listening on `127.0.0.1`. Default: `host`.\n\t */\n\tredirectHost?: string;\n\tport?: number;\n\tpath?: string;\n\t/** More paths that receive the callback, for example a server-specific path of a redirect URI. */\n\textraPaths?: string[];\n\ttimeoutMs?: number;\n\t/** Render the browser page as HTML. Default: a plain-text message. */\n\trenderPage?: (page: OAuthCallbackPage) => string;\n}\n\nfunction plainText(page: OAuthCallbackPage): string {\n\tif (page.ok) return \"Authorization complete. You may close this window.\";\n\treturn page.details ? `${page.message}\\n\\n${page.details}` : page.message;\n}\n\nexport class OAuthCallbackServer {\n\treadonly redirectUrl: string;\n\tprivate server: Server;\n\tprivate paths: string[];\n\tprivate timeoutMs: number;\n\tprivate renderPage: ((page: OAuthCallbackPage) => string) | undefined;\n\tprivate pending = new Map<\n\t\tstring,\n\t\t{\n\t\t\tresolve: (callback: OAuthCallback) => void;\n\t\t\treject: (error: Error) => void;\n\t\t\ttimer: ReturnType<typeof setTimeout>;\n\t\t\tpath: string | undefined;\n\t\t}\n\t>();\n\n\tprivate constructor(\n\t\tserver: Server,\n\t\tredirectUrl: string,\n\t\tpaths: string[],\n\t\ttimeoutMs: number,\n\t\trenderPage: ((page: OAuthCallbackPage) => string) | undefined,\n\t) {\n\t\tthis.server = server;\n\t\tthis.redirectUrl = redirectUrl;\n\t\tthis.paths = paths;\n\t\tthis.timeoutMs = timeoutMs;\n\t\tthis.renderPage = renderPage;\n\t}\n\n\tstatic async listen(options: OAuthCallbackServerOptions = {}): Promise<OAuthCallbackServer> {\n\t\tconst host = options.host ?? \"127.0.0.1\";\n\t\tconst redirectHost = options.redirectHost ?? host;\n\t\tconst path = options.path ?? \"/callback\";\n\t\tlet instance: OAuthCallbackServer | undefined;\n\t\tconst server = createServer((request, response) =>\n\t\t\tinstance?.handle(request.url ?? \"/\", request.headers.host, response),\n\t\t);\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tserver.once(\"error\", reject);\n\t\t\tserver.listen(options.port ?? 0, host, () => {\n\t\t\t\tserver.off(\"error\", reject);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t\tconst address = server.address();\n\t\tif (!address || typeof address === \"string\") throw new Error(\"OAuth callback server did not bind to TCP\");\n\t\tinstance = new OAuthCallbackServer(\n\t\t\tserver,\n\t\t\t`http://${redirectHost.includes(\":\") ? `[${redirectHost}]` : redirectHost}:${address.port}${path}`,\n\t\t\t[path, ...(options.extraPaths ?? [])],\n\t\t\toptions.timeoutMs ?? 5 * 60_000,\n\t\t\toptions.renderPage,\n\t\t);\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Wait for the authorization response with `state`. With `path`, a response on another path fails, so\n\t * a server-specific redirect URI can tell authorization servers apart (RFC 9700 section 4.4.2.2).\n\t */\n\twaitForCallback(state: string, path?: string): Promise<OAuthCallback> {\n\t\tif (this.pending.has(state)) throw new Error(\"OAuth state is already pending\");\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.pending.delete(state);\n\t\t\t\treject(new Error(\"OAuth callback timed out\"));\n\t\t\t}, this.timeoutMs);\n\t\t\tthis.pending.set(state, { resolve, reject, timer, path });\n\t\t});\n\t}\n\n\tasync close(): Promise<void> {\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tclearTimeout(pending.timer);\n\t\t\tpending.reject(new Error(\"OAuth callback server closed\"));\n\t\t}\n\t\tthis.pending.clear();\n\t\tconst closed = new Promise<void>((resolve, reject) => {\n\t\t\tthis.server.close((error) => (error ? reject(error) : resolve()));\n\t\t});\n\t\t// close() only stops accepting new connections and calls back once every connection has ended. A\n\t\t// browser may keep a connection open that has not sent a request (a preconnect or a spare keep-alive\n\t\t// socket), and Node does not count it as idle. Waiting for it can take minutes. The callback page has\n\t\t// been sent by now, so drop them all.\n\t\tthis.server.closeAllConnections();\n\t\tawait closed;\n\t}\n\n\tprivate reply(response: ServerResponse, status: number, page: OAuthCallbackPage): void {\n\t\tif (this.renderPage) {\n\t\t\tresponse.writeHead(status, { \"content-type\": \"text/html; charset=utf-8\", \"cache-control\": \"no-store\" });\n\t\t\tresponse.end(this.renderPage(page));\n\t\t} else {\n\t\t\tresponse.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" }).end(plainText(page));\n\t\t}\n\t}\n\n\tprivate handle(rawUrl: string, host: string | undefined, response: ServerResponse): void {\n\t\tconst url = new URL(rawUrl, this.redirectUrl);\n\t\tconst redirect = new URL(this.redirectUrl);\n\t\tif (host !== redirect.host || url.origin !== redirect.origin) {\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Unexpected redirect origin\" });\n\t\t\treturn;\n\t\t}\n\t\tif (!this.paths.includes(url.pathname)) {\n\t\t\tthis.reply(response, 404, { ok: false, message: \"Not found\" });\n\t\t\treturn;\n\t\t}\n\t\tconst state = url.searchParams.get(\"state\");\n\t\tconst pending = state ? this.pending.get(state) : undefined;\n\t\tif (!state || !pending) {\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Invalid or expired OAuth state\" });\n\t\t\treturn;\n\t\t}\n\t\t// Everything above (Host, origin, unknown path, unknown state) fails without touching the pending\n\t\t// sign-in. From here on the state is consumed, by design also on the wrong one of this server's paths:\n\t\t// a valid state on another redirect URI means an authorization server mixed up the response (RFC 9700\n\t\t// section 4.4.2.2), so the sign-in fails instead of waiting for a second response with the same state.\n\t\tclearTimeout(pending.timer);\n\t\tthis.pending.delete(state);\n\t\tif (pending.path !== undefined && url.pathname !== pending.path) {\n\t\t\tpending.reject(new Error(\"The authorization response arrived on another redirect URI\"));\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Unexpected redirect URI\" });\n\t\t\treturn;\n\t\t}\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tif (error) {\n\t\t\tconst description = url.searchParams.get(\"error_description\") ?? error;\n\t\t\tpending.reject(new Error(description));\n\t\t\tthis.reply(response, 200, {\n\t\t\t\tok: false,\n\t\t\t\tmessage: \"Authorization failed. You may close this window.\",\n\t\t\t\tdetails: description,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tif (!code) {\n\t\t\tpending.reject(new Error(\"OAuth callback did not include an authorization code\"));\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Missing authorization code\" });\n\t\t\treturn;\n\t\t}\n\t\tconst iss = url.searchParams.get(\"iss\");\n\t\tpending.resolve({ code, state, ...(iss ? { iss } : {}) });\n\t\tthis.reply(response, 200, { ok: true });\n\t}\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** One tool argument mirrored into a header: the `properties` path to it and the header name part. */
|
|
2
|
+
export interface ToolHeaderBinding {
|
|
3
|
+
path: string[];
|
|
4
|
+
header: string;
|
|
5
|
+
}
|
|
6
|
+
/** A tool's header bindings, or why its `x-mcp-header` annotations are invalid. */
|
|
7
|
+
export type ToolHeaderBindings = {
|
|
8
|
+
kind: "valid";
|
|
9
|
+
bindings: ToolHeaderBinding[];
|
|
10
|
+
} | {
|
|
11
|
+
kind: "invalid";
|
|
12
|
+
reason: string;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* A header value for `value`: as is when it is plain ASCII without leading or trailing whitespace,
|
|
16
|
+
* otherwise Base64 of its UTF-8 in the `=?base64?…?=` form. Values that look like that form are
|
|
17
|
+
* encoded too, so they are not mistaken for it.
|
|
18
|
+
*/
|
|
19
|
+
export declare function encodeHeaderValue(value: string): string;
|
|
20
|
+
/** `Mcp-Method`, and `Mcp-Name` for the methods that name a tool, prompt, or resource. */
|
|
21
|
+
export declare function standardRequestHeaders(method: string, params: unknown): Record<string, string>;
|
|
22
|
+
/**
|
|
23
|
+
* The arguments a tool mirrors into headers (wire input). Annotations are valid only on `string`,
|
|
24
|
+
* `integer`, and `boolean` properties reached from the schema root through `properties` alone, with
|
|
25
|
+
* non-empty token names that are unique ignoring case. Clients on HTTP exclude tools with an invalid
|
|
26
|
+
* annotation.
|
|
27
|
+
*/
|
|
28
|
+
export declare function toolHeaderBindings(inputSchema: Record<string, unknown>): ToolHeaderBindings;
|
|
29
|
+
/** `Mcp-Param-*` headers for a tool call. Arguments that are absent, null, or not primitive get no header. */
|
|
30
|
+
export declare function toolParamHeaders(bindings: readonly ToolHeaderBinding[], args: Record<string, unknown> | undefined): Record<string, string>;
|
|
31
|
+
//# sourceMappingURL=http-headers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http-headers.d.ts","sourceRoot":"","sources":["../../src/protocol/http-headers.ts"],"names":[],"mappings":"AAIA,sGAAsG;AACtG,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CACf;AAED,mFAAmF;AACnF,MAAM,MAAM,kBAAkB,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,QAAQ,EAAE,iBAAiB,EAAE,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAYxH;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOvD;AAED,0FAA0F;AAC1F,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQ9F;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,kBAAkB,CAwC3F;AAmBD,8GAA8G;AAC9G,wBAAgB,gBAAgB,CAC/B,QAAQ,EAAE,SAAS,iBAAiB,EAAE,EACtC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,GACvC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CASxB"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// HTTP headers that MCP 2026-07-28 mirrors from the request body: `Mcp-Method`, `Mcp-Name`, and
|
|
2
|
+
// `Mcp-Param-*` for tool arguments a tool's input schema marks with `x-mcp-header`.
|
|
3
|
+
import { isObject } from "./jsonrpc.js";
|
|
4
|
+
const HEADER_ANNOTATION = "x-mcp-header";
|
|
5
|
+
const BASE64_SENTINEL = /^=\?base64\?.*\?=$/s;
|
|
6
|
+
// RFC 9110 token characters.
|
|
7
|
+
const HEADER_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
8
|
+
const PRIMITIVE_TYPES = new Set(["string", "integer", "boolean"]);
|
|
9
|
+
// Input schemas come from the server; deeper nesting is not worth walking.
|
|
10
|
+
const MAX_SCHEMA_DEPTH = 64;
|
|
11
|
+
// Keywords whose values are instance data, not schemas, so an `x-mcp-header` key in them is no annotation.
|
|
12
|
+
const DATA_KEYWORDS = new Set(["const", "default", "enum", "examples"]);
|
|
13
|
+
/**
|
|
14
|
+
* A header value for `value`: as is when it is plain ASCII without leading or trailing whitespace,
|
|
15
|
+
* otherwise Base64 of its UTF-8 in the `=?base64?…?=` form. Values that look like that form are
|
|
16
|
+
* encoded too, so they are not mistaken for it.
|
|
17
|
+
*/
|
|
18
|
+
export function encodeHeaderValue(value) {
|
|
19
|
+
let plain = value === value.trim() && !BASE64_SENTINEL.test(value);
|
|
20
|
+
for (let i = 0; plain && i < value.length; i++) {
|
|
21
|
+
const code = value.charCodeAt(i);
|
|
22
|
+
plain = code >= 0x20 && code <= 0x7e;
|
|
23
|
+
}
|
|
24
|
+
return plain ? value : `=?base64?${Buffer.from(value, "utf8").toString("base64")}?=`;
|
|
25
|
+
}
|
|
26
|
+
/** `Mcp-Method`, and `Mcp-Name` for the methods that name a tool, prompt, or resource. */
|
|
27
|
+
export function standardRequestHeaders(method, params) {
|
|
28
|
+
const headers = { "Mcp-Method": method };
|
|
29
|
+
const name = method === "resources/read"
|
|
30
|
+
? isObject(params) && params.uri
|
|
31
|
+
: (method === "tools/call" || method === "prompts/get") && isObject(params) && params.name;
|
|
32
|
+
if (typeof name === "string")
|
|
33
|
+
headers["Mcp-Name"] = encodeHeaderValue(name);
|
|
34
|
+
return headers;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The arguments a tool mirrors into headers (wire input). Annotations are valid only on `string`,
|
|
38
|
+
* `integer`, and `boolean` properties reached from the schema root through `properties` alone, with
|
|
39
|
+
* non-empty token names that are unique ignoring case. Clients on HTTP exclude tools with an invalid
|
|
40
|
+
* annotation.
|
|
41
|
+
*/
|
|
42
|
+
export function toolHeaderBindings(inputSchema) {
|
|
43
|
+
const bindings = [];
|
|
44
|
+
const seen = new Set();
|
|
45
|
+
let problem;
|
|
46
|
+
const visit = (schema, path, depth) => {
|
|
47
|
+
if (problem || depth > MAX_SCHEMA_DEPTH)
|
|
48
|
+
return;
|
|
49
|
+
if (Array.isArray(schema)) {
|
|
50
|
+
for (const item of schema)
|
|
51
|
+
visit(item, undefined, depth + 1);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
if (!isObject(schema))
|
|
55
|
+
return;
|
|
56
|
+
if (HEADER_ANNOTATION in schema) {
|
|
57
|
+
if (!path) {
|
|
58
|
+
problem = `${HEADER_ANNOTATION} outside of nested properties`;
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const annotation = readAnnotation(schema, seen);
|
|
62
|
+
if (annotation.kind === "invalid") {
|
|
63
|
+
problem = annotation.reason;
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
seen.add(annotation.header.toLowerCase());
|
|
67
|
+
bindings.push({ path, header: annotation.header });
|
|
68
|
+
}
|
|
69
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
70
|
+
if (key === "properties" && path && isObject(value)) {
|
|
71
|
+
for (const [name, property] of Object.entries(value))
|
|
72
|
+
visit(property, [...path, name], depth + 1);
|
|
73
|
+
}
|
|
74
|
+
else if (key !== HEADER_ANNOTATION && !DATA_KEYWORDS.has(key)) {
|
|
75
|
+
visit(value, undefined, depth + 1);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
if (isObject(inputSchema.properties)) {
|
|
80
|
+
for (const [name, property] of Object.entries(inputSchema.properties))
|
|
81
|
+
visit(property, [name], 1);
|
|
82
|
+
}
|
|
83
|
+
for (const [key, value] of Object.entries(inputSchema)) {
|
|
84
|
+
if (key === HEADER_ANNOTATION)
|
|
85
|
+
problem ??= `${HEADER_ANNOTATION} on the schema root`;
|
|
86
|
+
else if (key !== "properties" && !DATA_KEYWORDS.has(key))
|
|
87
|
+
visit(value, undefined, 1);
|
|
88
|
+
}
|
|
89
|
+
return problem ? { kind: "invalid", reason: problem } : { kind: "valid", bindings };
|
|
90
|
+
}
|
|
91
|
+
/** The header name of a property's annotation, or why the annotation is invalid. */
|
|
92
|
+
function readAnnotation(schema, seen) {
|
|
93
|
+
const header = schema[HEADER_ANNOTATION];
|
|
94
|
+
const invalid = (reason) => ({ kind: "invalid", reason: `${HEADER_ANNOTATION} ${reason}` });
|
|
95
|
+
if (typeof header !== "string" || header === "")
|
|
96
|
+
return invalid("must be a non-empty string");
|
|
97
|
+
if (!HEADER_TOKEN.test(header))
|
|
98
|
+
return invalid(`"${header}" is not a valid header name`);
|
|
99
|
+
if (seen.has(header.toLowerCase()))
|
|
100
|
+
return invalid(`"${header}" is not unique`);
|
|
101
|
+
const types = Array.isArray(schema.type) ? schema.type.filter((type) => type !== "null") : [schema.type];
|
|
102
|
+
if (types.length !== 1 || typeof types[0] !== "string" || !PRIMITIVE_TYPES.has(types[0])) {
|
|
103
|
+
return invalid(`"${header}" must be on a string, integer, or boolean property`);
|
|
104
|
+
}
|
|
105
|
+
return { kind: "valid", header };
|
|
106
|
+
}
|
|
107
|
+
/** `Mcp-Param-*` headers for a tool call. Arguments that are absent, null, or not primitive get no header. */
|
|
108
|
+
export function toolParamHeaders(bindings, args) {
|
|
109
|
+
const headers = {};
|
|
110
|
+
for (const { path, header } of bindings) {
|
|
111
|
+
let value = args;
|
|
112
|
+
for (const key of path)
|
|
113
|
+
value = isObject(value) ? value[key] : undefined;
|
|
114
|
+
const encoded = paramHeaderValue(value);
|
|
115
|
+
if (encoded !== undefined)
|
|
116
|
+
headers[`Mcp-Param-${header}`] = encoded;
|
|
117
|
+
}
|
|
118
|
+
return headers;
|
|
119
|
+
}
|
|
120
|
+
function paramHeaderValue(value) {
|
|
121
|
+
if (typeof value === "string")
|
|
122
|
+
return encodeHeaderValue(value);
|
|
123
|
+
if (typeof value === "boolean")
|
|
124
|
+
return String(value);
|
|
125
|
+
if (typeof value === "number" && Number.isInteger(value))
|
|
126
|
+
return String(value);
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
//# sourceMappingURL=http-headers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,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AAC","sourcesContent":["// HTTP headers that MCP 2026-07-28 mirrors from the request body: `Mcp-Method`, `Mcp-Name`, and\n// `Mcp-Param-*` for tool arguments a tool's input schema marks with `x-mcp-header`.\nimport { isObject } from \"./jsonrpc.ts\";\n\n/** One tool argument mirrored into a header: the `properties` path to it and the header name part. */\nexport interface ToolHeaderBinding {\n\tpath: string[];\n\theader: string;\n}\n\n/** A tool's header bindings, or why its `x-mcp-header` annotations are invalid. */\nexport type ToolHeaderBindings = { kind: \"valid\"; bindings: ToolHeaderBinding[] } | { kind: \"invalid\"; reason: string };\n\nconst HEADER_ANNOTATION = \"x-mcp-header\";\nconst BASE64_SENTINEL = /^=\\?base64\\?.*\\?=$/s;\n// RFC 9110 token characters.\nconst HEADER_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst PRIMITIVE_TYPES = new Set([\"string\", \"integer\", \"boolean\"]);\n// Input schemas come from the server; deeper nesting is not worth walking.\nconst MAX_SCHEMA_DEPTH = 64;\n// Keywords whose values are instance data, not schemas, so an `x-mcp-header` key in them is no annotation.\nconst DATA_KEYWORDS = new Set([\"const\", \"default\", \"enum\", \"examples\"]);\n\n/**\n * A header value for `value`: as is when it is plain ASCII without leading or trailing whitespace,\n * otherwise Base64 of its UTF-8 in the `=?base64?…?=` form. Values that look like that form are\n * encoded too, so they are not mistaken for it.\n */\nexport function encodeHeaderValue(value: string): string {\n\tlet plain = value === value.trim() && !BASE64_SENTINEL.test(value);\n\tfor (let i = 0; plain && i < value.length; i++) {\n\t\tconst code = value.charCodeAt(i);\n\t\tplain = code >= 0x20 && code <= 0x7e;\n\t}\n\treturn plain ? value : `=?base64?${Buffer.from(value, \"utf8\").toString(\"base64\")}?=`;\n}\n\n/** `Mcp-Method`, and `Mcp-Name` for the methods that name a tool, prompt, or resource. */\nexport function standardRequestHeaders(method: string, params: unknown): Record<string, string> {\n\tconst headers: Record<string, string> = { \"Mcp-Method\": method };\n\tconst name =\n\t\tmethod === \"resources/read\"\n\t\t\t? isObject(params) && params.uri\n\t\t\t: (method === \"tools/call\" || method === \"prompts/get\") && isObject(params) && params.name;\n\tif (typeof name === \"string\") headers[\"Mcp-Name\"] = encodeHeaderValue(name);\n\treturn headers;\n}\n\n/**\n * The arguments a tool mirrors into headers (wire input). Annotations are valid only on `string`,\n * `integer`, and `boolean` properties reached from the schema root through `properties` alone, with\n * non-empty token names that are unique ignoring case. Clients on HTTP exclude tools with an invalid\n * annotation.\n */\nexport function toolHeaderBindings(inputSchema: Record<string, unknown>): ToolHeaderBindings {\n\tconst bindings: ToolHeaderBinding[] = [];\n\tconst seen = new Set<string>();\n\tlet problem: string | undefined;\n\tconst visit = (schema: unknown, path: string[] | undefined, depth: number): void => {\n\t\tif (problem || depth > MAX_SCHEMA_DEPTH) return;\n\t\tif (Array.isArray(schema)) {\n\t\t\tfor (const item of schema) visit(item, undefined, depth + 1);\n\t\t\treturn;\n\t\t}\n\t\tif (!isObject(schema)) return;\n\t\tif (HEADER_ANNOTATION in schema) {\n\t\t\tif (!path) {\n\t\t\t\tproblem = `${HEADER_ANNOTATION} outside of nested properties`;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst annotation = readAnnotation(schema, seen);\n\t\t\tif (annotation.kind === \"invalid\") {\n\t\t\t\tproblem = annotation.reason;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tseen.add(annotation.header.toLowerCase());\n\t\t\tbindings.push({ path, header: annotation.header });\n\t\t}\n\t\tfor (const [key, value] of Object.entries(schema)) {\n\t\t\tif (key === \"properties\" && path && isObject(value)) {\n\t\t\t\tfor (const [name, property] of Object.entries(value)) visit(property, [...path, name], depth + 1);\n\t\t\t} else if (key !== HEADER_ANNOTATION && !DATA_KEYWORDS.has(key)) {\n\t\t\t\tvisit(value, undefined, depth + 1);\n\t\t\t}\n\t\t}\n\t};\n\tif (isObject(inputSchema.properties)) {\n\t\tfor (const [name, property] of Object.entries(inputSchema.properties)) visit(property, [name], 1);\n\t}\n\tfor (const [key, value] of Object.entries(inputSchema)) {\n\t\tif (key === HEADER_ANNOTATION) problem ??= `${HEADER_ANNOTATION} on the schema root`;\n\t\telse if (key !== \"properties\" && !DATA_KEYWORDS.has(key)) visit(value, undefined, 1);\n\t}\n\treturn problem ? { kind: \"invalid\", reason: problem } : { kind: \"valid\", bindings };\n}\n\n/** The header name of a property's annotation, or why the annotation is invalid. */\nfunction readAnnotation(\n\tschema: Record<string, unknown>,\n\tseen: Set<string>,\n): { kind: \"valid\"; header: string } | { kind: \"invalid\"; reason: string } {\n\tconst header = schema[HEADER_ANNOTATION];\n\tconst invalid = (reason: string) => ({ kind: \"invalid\" as const, reason: `${HEADER_ANNOTATION} ${reason}` });\n\tif (typeof header !== \"string\" || header === \"\") return invalid(\"must be a non-empty string\");\n\tif (!HEADER_TOKEN.test(header)) return invalid(`\"${header}\" is not a valid header name`);\n\tif (seen.has(header.toLowerCase())) return invalid(`\"${header}\" is not unique`);\n\tconst types = Array.isArray(schema.type) ? schema.type.filter((type) => type !== \"null\") : [schema.type];\n\tif (types.length !== 1 || typeof types[0] !== \"string\" || !PRIMITIVE_TYPES.has(types[0])) {\n\t\treturn invalid(`\"${header}\" must be on a string, integer, or boolean property`);\n\t}\n\treturn { kind: \"valid\", header };\n}\n\n/** `Mcp-Param-*` headers for a tool call. Arguments that are absent, null, or not primitive get no header. */\nexport function toolParamHeaders(\n\tbindings: readonly ToolHeaderBinding[],\n\targs: Record<string, unknown> | undefined,\n): Record<string, string> {\n\tconst headers: Record<string, string> = {};\n\tfor (const { path, header } of bindings) {\n\t\tlet value: unknown = args;\n\t\tfor (const key of path) value = isObject(value) ? value[key] : undefined;\n\t\tconst encoded = paramHeaderValue(value);\n\t\tif (encoded !== undefined) headers[`Mcp-Param-${header}`] = encoded;\n\t}\n\treturn headers;\n}\n\nfunction paramHeaderValue(value: unknown): string | undefined {\n\tif (typeof value === \"string\") return encodeHeaderValue(value);\n\tif (typeof value === \"boolean\") return String(value);\n\tif (typeof value === \"number\" && Number.isInteger(value)) return String(value);\n\treturn undefined;\n}\n"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { ClientCapabilities, DiscoverResult, Implementation, InputRequest, LoggingLevel, STATELESS_PROTOCOL_VERSION, SubscriptionFilter } from "./types.ts";
|
|
2
|
+
/** Error code of a request whose `Mcp-*` headers do not match its body (MCP 2026-07-28). */
|
|
3
|
+
export declare const HEADER_MISMATCH_ERROR_CODE = -32020;
|
|
4
|
+
/**
|
|
5
|
+
* Error codes MCP 2026-07-28 reserves: header mismatch, missing required client capability, and
|
|
6
|
+
* unsupported protocol version. Only servers of that revision send them.
|
|
7
|
+
*/
|
|
8
|
+
export declare const STATELESS_ERROR_CODES: readonly number[];
|
|
9
|
+
/** What every stateless request declares about the client in its `_meta`. */
|
|
10
|
+
export interface StatelessRequestMeta {
|
|
11
|
+
protocolVersion: typeof STATELESS_PROTOCOL_VERSION;
|
|
12
|
+
clientInfo: Implementation;
|
|
13
|
+
clientCapabilities: ClientCapabilities;
|
|
14
|
+
logLevel: LoggingLevel | undefined;
|
|
15
|
+
}
|
|
16
|
+
/** `params` with the stateless request metadata added to its `_meta`, keeping the `_meta` keys it has. */
|
|
17
|
+
export declare function withStatelessMeta(params: Record<string, unknown> | undefined, meta: StatelessRequestMeta): Record<string, unknown>;
|
|
18
|
+
/** A result of a stateless request, by `resultType`. */
|
|
19
|
+
export type StatelessResult = {
|
|
20
|
+
kind: "complete";
|
|
21
|
+
result: unknown;
|
|
22
|
+
} | {
|
|
23
|
+
kind: "input_required";
|
|
24
|
+
inputRequests: Record<string, InputRequest>;
|
|
25
|
+
requestState: string | undefined;
|
|
26
|
+
}
|
|
27
|
+
/** A result type an MCP extension defines (`upload_required`, say); the whole result, unchecked. */
|
|
28
|
+
| {
|
|
29
|
+
kind: "extension";
|
|
30
|
+
resultType: string;
|
|
31
|
+
result: Record<string, unknown>;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Read the `resultType` of a stateless result (wire input). A result without one is complete; other
|
|
35
|
+
* result types than the base protocol's are left to the caller, which knows the extensions it supports.
|
|
36
|
+
*/
|
|
37
|
+
export declare function readStatelessResult(method: string, value: unknown): StatelessResult;
|
|
38
|
+
/** Validate a `server/discover` result (wire input), with the server's name and version from its `_meta`. */
|
|
39
|
+
export declare function validateDiscoverResult(value: unknown): {
|
|
40
|
+
result: DiscoverResult;
|
|
41
|
+
serverInfo?: Implementation;
|
|
42
|
+
};
|
|
43
|
+
/** The subscription a notification belongs to (`_meta`), by the id of its `subscriptions/listen` request. */
|
|
44
|
+
export declare function subscriptionIdOf(params: unknown): unknown;
|
|
45
|
+
/** The notification types a `notifications/subscriptions/acknowledged` agrees to (wire input); others are left out. */
|
|
46
|
+
export declare function readSubscriptionFilter(params: unknown): SubscriptionFilter;
|
|
47
|
+
//# sourceMappingURL=stateless.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stateless.d.ts","sourceRoot":"","sources":["../../src/protocol/stateless.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACX,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,YAAY,EACZ,YAAY,EACZ,0BAA0B,EAC1B,kBAAkB,EAClB,MAAM,YAAY,CAAC;AAEpB,4FAA4F;AAC5F,eAAO,MAAM,0BAA0B,SAAS,CAAC;AAEjD;;;GAGG;AACH,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAAiD,CAAC;AAErG,6EAA6E;AAC7E,MAAM,WAAW,oBAAoB;IACpC,eAAe,EAAE,OAAO,0BAA0B,CAAC;IACnD,UAAU,EAAE,cAAc,CAAC;IAC3B,kBAAkB,EAAE,kBAAkB,CAAC;IACvC,QAAQ,EAAE,YAAY,GAAG,SAAS,CAAC;CACnC;AAED,0GAA0G;AAC1G,wBAAgB,iBAAiB,CAChC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC3C,IAAI,EAAE,oBAAoB,GACxB,M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