mcp-expose 1.1.0 → 1.1.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/CHANGELOG.md +33 -1
- package/README.md +143 -34
- package/dist/adonisjs/index.cjs +128 -6
- package/dist/adonisjs/index.cjs.map +1 -1
- package/dist/adonisjs/index.d.cts +1 -1
- package/dist/adonisjs/index.d.ts +1 -1
- package/dist/adonisjs/index.js +128 -6
- package/dist/adonisjs/index.js.map +1 -1
- package/dist/express/index.cjs +128 -6
- package/dist/express/index.cjs.map +1 -1
- package/dist/express/index.d.cts +1 -1
- package/dist/express/index.d.ts +1 -1
- package/dist/express/index.js +128 -6
- package/dist/express/index.js.map +1 -1
- package/dist/fastify/index.cjs +128 -6
- package/dist/fastify/index.cjs.map +1 -1
- package/dist/fastify/index.d.cts +1 -1
- package/dist/fastify/index.d.ts +1 -1
- package/dist/fastify/index.js +128 -6
- package/dist/fastify/index.js.map +1 -1
- package/dist/hono/index.cjs +128 -6
- package/dist/hono/index.cjs.map +1 -1
- package/dist/hono/index.d.cts +1 -1
- package/dist/hono/index.d.ts +1 -1
- package/dist/hono/index.js +128 -6
- package/dist/hono/index.js.map +1 -1
- package/dist/index.cjs +128 -31
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -5
- package/dist/index.d.ts +7 -5
- package/dist/index.js +128 -31
- package/dist/index.js.map +1 -1
- package/dist/koa/index.cjs +128 -6
- package/dist/koa/index.cjs.map +1 -1
- package/dist/koa/index.d.cts +1 -1
- package/dist/koa/index.d.ts +1 -1
- package/dist/koa/index.js +128 -6
- package/dist/koa/index.js.map +1 -1
- package/dist/nestjs/index.cjs +128 -6
- package/dist/nestjs/index.cjs.map +1 -1
- package/dist/nestjs/index.d.cts +1 -1
- package/dist/nestjs/index.d.ts +1 -1
- package/dist/nestjs/index.js +128 -6
- package/dist/nestjs/index.js.map +1 -1
- package/dist/{server-BFQ_Hdh9.d.cts → server--mQVQq3A.d.cts} +55 -2
- package/dist/{server-BRw1E2xy.d.ts → server-BPDTsT2o.d.ts} +55 -2
- package/package.json +2 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/core/oauth.ts","../src/core/server.ts","../src/core/schema.ts","../src/core/route-tool.ts","../src/core/dispatch.ts","../src/core/define.ts"],"sourcesContent":["/**\n * Public API of `mcp-expose` (framework-agnostic core).\n * Framework adapters live in `mcp-expose/<framework>`.\n */\nexport * from './core/types.js';\nexport { McpServer, SUPPORTED_PROTOCOL_VERSIONS, LATEST_PROTOCOL_VERSION } from './core/server.js';\nexport type { McpHttpRequest, McpHttpResponse, JsonRpcResponse } from './core/server.js';\nexport { createRouteTool, DEFAULT_FORWARD_HEADERS } from './core/route-tool.js';\nexport { createFetchDispatcher } from './core/dispatch.js';\nexport type { FetchDispatcherOptions } from './core/dispatch.js';\nexport { defineTool, toolsFromOpenApi, toToolResult } from './core/define.js';\nexport type { DefineToolOptions, FromOpenApiOptions } from './core/define.js';\nexport { toJsonSchema } from './core/schema.js';\nexport {\n bearerChallenge,\n parseScopes,\n protectedResourceMetadataPaths,\n protectedResourceMetadataUrl,\n} from './core/oauth.js';\n","/**\n * OAuth 2.1 support per the MCP authorization spec: the MCP endpoint acts as an\n * OAuth *resource server*. It publishes Protected Resource Metadata (RFC 9728),\n * answers unauthenticated requests with a `WWW-Authenticate` challenge that\n * tells the client where to log in, and checks bearer tokens with a verifier\n * you provide (see `jwtVerifier` / `introspectionVerifier` in `mcp-expose/oauth`).\n *\n * Runtime-agnostic: no `node:*` imports.\n */\n\n/** Who the access token belongs to and what it allows. Available to tools as `ctx.auth`. */\nexport interface AuthInfo {\n /** The raw access token. */\n token: string;\n /** Scopes granted to the token. */\n scopes: string[];\n /** Subject (user id), e.g. the JWT `sub` claim. */\n subject?: string;\n /** OAuth client the token was issued to. */\n clientId?: string;\n /** Expiry, in seconds since the epoch. Expired tokens are rejected. */\n expiresAt?: number;\n /** All claims / introspection fields. */\n claims?: Record<string, unknown>;\n}\n\nexport interface VerifyTokenContext {\n /** The canonical resource URL (`oauth.resource`). Tokens must be issued for it (audience). */\n resource: string;\n /** Lower-cased headers of the MCP request. */\n headers: Record<string, string>;\n}\n\n/**\n * Checks an access token. Return its AuthInfo, or `undefined` / throw when the\n * token is invalid. It MUST check that the token was issued for this server\n * (audience = `ctx.resource`), or tokens meant for other services would be accepted.\n */\nexport type TokenVerifier = (\n token: string,\n ctx: VerifyTokenContext,\n) => AuthInfo | undefined | null | Promise<AuthInfo | undefined | null>;\n\nexport interface OAuthOptions {\n /**\n * Canonical, public URL of the MCP endpoint, e.g. `https://api.example.com/mcp`.\n * Clients request tokens for this resource, and it must match the URL they connect to.\n */\n resource: string;\n /** Issuer URLs of the authorization servers that issue tokens for this server. */\n authorizationServers: string[];\n /** Checks bearer tokens. */\n verifyToken: TokenVerifier;\n /** Scopes every token needs to use the MCP endpoint at all. */\n requiredScopes?: string[];\n /** Scopes advertised in the metadata. @default requiredScopes plus every tool's `scopes` */\n scopesSupported?: string[];\n /** Human-readable name shown by clients. */\n resourceName?: string;\n /** URL of documentation for developers. */\n resourceDocumentation?: string;\n /** Extra fields merged into the Protected Resource Metadata document. */\n metadata?: Record<string, unknown>;\n}\n\nexport const PROTECTED_RESOURCE_WELL_KNOWN = '/.well-known/oauth-protected-resource';\n\n/**\n * Paths the metadata is served on, per RFC 9728: the well-known prefix with the\n * resource path appended (`/.well-known/oauth-protected-resource/mcp`), plus the\n * bare well-known path that older clients fall back to.\n */\nexport function protectedResourceMetadataPaths(resource: string): string[] {\n const pathname = new URL(resource).pathname.replace(/\\/+$/, '');\n return pathname\n ? [PROTECTED_RESOURCE_WELL_KNOWN + pathname, PROTECTED_RESOURCE_WELL_KNOWN]\n : [PROTECTED_RESOURCE_WELL_KNOWN];\n}\n\n/** Absolute URL of the metadata document, used in `WWW-Authenticate`. */\nexport function protectedResourceMetadataUrl(resource: string): string {\n return new URL(protectedResourceMetadataPaths(resource)[0] as string, resource).href;\n}\n\nexport function validateOAuthOptions(o: OAuthOptions): void {\n let url: URL;\n try {\n url = new URL(o.resource);\n } catch {\n throw new Error(`mcp-expose: oauth.resource must be an absolute URL, got ${JSON.stringify(o.resource)}`);\n }\n if (url.hash) throw new Error('mcp-expose: oauth.resource must not contain a fragment');\n if (!o.authorizationServers?.length) throw new Error('mcp-expose: oauth.authorizationServers must not be empty');\n if (typeof o.verifyToken !== 'function') throw new Error('mcp-expose: oauth.verifyToken is required');\n}\n\nconst quote = (v: string) => `\"${v.replace(/[\"\\\\]/g, '\\\\$&')}\"`;\n\n/** Build a `WWW-Authenticate: Bearer ...` challenge (RFC 6750 + RFC 9728). */\nexport function bearerChallenge(\n resource: string,\n params: { error?: string; errorDescription?: string; scope?: string[] } = {},\n): string {\n const parts: string[] = [];\n if (params.error) parts.push(`error=${quote(params.error)}`);\n if (params.errorDescription) parts.push(`error_description=${quote(params.errorDescription)}`);\n if (params.scope?.length) parts.push(`scope=${quote(params.scope.join(' '))}`);\n parts.push(`resource_metadata=${quote(protectedResourceMetadataUrl(resource))}`);\n return `Bearer ${parts.join(', ')}`;\n}\n\n/** Extract the token from `Authorization: Bearer <token>`. Tokens in the query string are never accepted. */\nexport function bearerToken(headers: Record<string, string>): string | undefined {\n const m = /^Bearer[ ]+([^\\s,]+)\\s*$/i.exec(headers.authorization ?? '');\n return m?.[1];\n}\n\nexport type AuthOutcome =\n | { ok: true; auth: AuthInfo }\n | { ok: false; status: 401 | 403; challenge: string; error: string; description: string };\n\n/** Authenticate one MCP request. */\nexport async function authenticate(o: OAuthOptions, headers: Record<string, string>): Promise<AuthOutcome> {\n const token = bearerToken(headers);\n if (!token) {\n // No credentials: a bare challenge pointing at the metadata starts the client's login flow.\n return {\n ok: false,\n status: 401,\n error: 'unauthorized',\n description: 'Authorization required',\n challenge: bearerChallenge(o.resource, { scope: o.requiredScopes }),\n };\n }\n\n let auth: AuthInfo | undefined | null;\n try {\n auth = await o.verifyToken(token, { resource: o.resource, headers });\n } catch {\n auth = undefined;\n }\n if (!auth) return deny(o, 401, 'invalid_token', 'The access token is invalid');\n if (auth.expiresAt !== undefined && auth.expiresAt * 1000 <= Date.now()) {\n return deny(o, 401, 'invalid_token', 'The access token has expired');\n }\n const missing = missingScopes(auth, o.requiredScopes);\n if (missing.length) {\n // Keep the scopes already granted in the challenge, so re-authorizing never drops access.\n const scope = [...new Set([...(auth.scopes ?? []), ...(o.requiredScopes ?? [])])];\n return deny(o, 403, 'insufficient_scope', `Missing scope: ${missing.join(' ')}`, scope);\n }\n return { ok: true, auth: { ...auth, scopes: auth.scopes ?? [] } };\n}\n\n/** A failed AuthOutcome with an RFC 6750 error challenge. */\nexport function deny(\n o: OAuthOptions,\n status: 401 | 403,\n error: string,\n description: string,\n scope?: string[],\n): AuthOutcome & { ok: false } {\n return {\n ok: false,\n status,\n error,\n description,\n challenge: bearerChallenge(o.resource, { error, errorDescription: description, scope }),\n };\n}\n\nexport function missingScopes(auth: AuthInfo | undefined, required: string[] | undefined): string[] {\n if (!required?.length) return [];\n const granted = new Set(auth?.scopes ?? []);\n return required.filter((s) => !granted.has(s));\n}\n\n/** Parse a space-separated `scope` string or an array of scopes. */\nexport function parseScopes(value: unknown): string[] {\n if (Array.isArray(value)) return value.map(String);\n if (typeof value === 'string') return value.split(' ').filter(Boolean);\n return [];\n}\n","import { authenticate, deny, missingScopes, protectedResourceMetadataPaths, validateOAuthOptions } from './oauth.js';\nimport type { McpServerOptions, McpToolDefinition, ToolContext, ToolResult } from './types.js';\n\nexport const SUPPORTED_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];\nexport const LATEST_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0] as string;\n\ntype JsonRpcId = string | number | null;\ninterface JsonRpcRequest {\n jsonrpc: '2.0';\n id?: JsonRpcId;\n method: string;\n params?: Record<string, unknown>;\n}\nexport interface JsonRpcResponse {\n jsonrpc: '2.0';\n id: JsonRpcId;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nconst PARSE_ERROR = -32700;\nconst INVALID_REQUEST = -32600;\nconst METHOD_NOT_FOUND = -32601;\nconst INVALID_PARAMS = -32602;\n\nconst ok = (id: JsonRpcId, result: unknown): JsonRpcResponse => ({ jsonrpc: '2.0', id, result });\nconst fail = (id: JsonRpcId, code: number, message: string): JsonRpcResponse => ({\n jsonrpc: '2.0',\n id,\n error: { code, message },\n});\n\n/** Minimal HTTP request/response shapes, so each adapter can bridge its own framework. */\nexport interface McpHttpRequest {\n method: string;\n headers: Record<string, string>;\n /** Parsed JSON body, or the raw string. */\n body: unknown;\n}\nexport interface McpHttpResponse {\n status: number;\n headers: Record<string, string>;\n body?: string;\n}\n\n/**\n * A stateless MCP server speaking the Streamable HTTP transport (JSON responses).\n * Holds the tool registry and answers JSON-RPC messages.\n */\nexport class McpServer {\n private readonly tools = new Map<string, McpToolDefinition>();\n private loaders: (() => void | Promise<void>)[] = [];\n\n constructor(readonly options: McpServerOptions) {\n if (options.oauth) validateOAuthOptions(options.oauth);\n }\n\n /** Register a tool. Throws on duplicate names. */\n addTool(tool: McpToolDefinition): this {\n if (this.tools.has(tool.name)) {\n throw new Error(`mcp-expose: duplicate tool name \"${tool.name}\". Set an explicit \\`name\\`.`);\n }\n this.tools.set(tool.name, tool);\n return this;\n }\n\n /** Register a function that adds tools lazily, right before the first MCP request is served. */\n onLoad(loader: () => void | Promise<void>): this {\n this.loaders.push(loader);\n return this;\n }\n\n async listTools(): Promise<McpToolDefinition[]> {\n await this.load();\n return [...this.tools.values()];\n }\n\n private async load() {\n if (!this.loaders.length) return;\n const loaders = this.loaders;\n this.loaders = [];\n for (const l of loaders) await l();\n }\n\n /** Handle one JSON-RPC message (or a batch). Returns null when no response is due. */\n async handleMessage(message: unknown, ctx: ToolContext): Promise<JsonRpcResponse | JsonRpcResponse[] | null> {\n if (Array.isArray(message)) {\n const results = (await Promise.all(message.map((m) => this.handleOne(m, ctx)))).filter(\n (r): r is JsonRpcResponse => r !== null,\n );\n return results.length ? results : null;\n }\n return this.handleOne(message, ctx);\n }\n\n private async handleOne(message: unknown, ctx: ToolContext): Promise<JsonRpcResponse | null> {\n const msg = message as Partial<JsonRpcRequest>;\n if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0') {\n return fail(null, INVALID_REQUEST, 'Invalid JSON-RPC message');\n }\n // Responses from the client or notifications: acknowledge, no reply.\n if (typeof msg.method !== 'string' || msg.id === undefined) return null;\n const id = msg.id;\n const params = msg.params ?? {};\n\n await this.load();\n switch (msg.method) {\n case 'initialize': {\n const requested = params.protocolVersion as string | undefined;\n const protocolVersion =\n requested && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;\n return ok(id, {\n protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: { name: this.options.name, version: this.options.version ?? '1.0.0' },\n ...(this.options.instructions ? { instructions: this.options.instructions } : {}),\n });\n }\n case 'ping':\n return ok(id, {});\n case 'tools/list':\n return ok(id, {\n tools: [...this.tools.values()].map((t) => ({\n name: t.name,\n ...(t.title ? { title: t.title } : {}),\n description: t.description,\n inputSchema: t.inputSchema,\n ...(t.annotations ? { annotations: t.annotations } : {}),\n })),\n });\n case 'tools/call': {\n const tool = this.tools.get(params.name as string);\n if (!tool) return fail(id, INVALID_PARAMS, `Unknown tool: ${String(params.name)}`);\n return ok(id, await this.callTool(tool, (params.arguments ?? {}) as Record<string, unknown>, ctx));\n }\n case 'resources/list':\n return ok(id, { resources: [] });\n case 'prompts/list':\n return ok(id, { prompts: [] });\n default:\n return fail(id, METHOD_NOT_FOUND, `Method not found: ${msg.method}`);\n }\n }\n\n private async callTool(\n tool: McpToolDefinition,\n args: Record<string, unknown>,\n ctx: ToolContext,\n ): Promise<ToolResult> {\n try {\n if (tool.validate) {\n const v = await tool.validate(args);\n if (!v.ok) return { isError: true, content: [{ type: 'text', text: `Invalid arguments: ${v.message}` }] };\n args = v.value as Record<string, unknown>;\n }\n return await tool.handler(args, ctx);\n } catch (err) {\n // Tool failures are reported in-band so the model can react to them.\n return { isError: true, content: [{ type: 'text', text: `Tool error: ${(err as Error).message}` }] };\n }\n }\n\n /** Check the Origin header (DNS rebinding protection). */\n isOriginAllowed(origin: string | undefined): boolean {\n if (!origin) return true;\n const allowed = this.options.allowedOrigins;\n if (allowed === '*') return true;\n return (allowed ?? []).includes(origin);\n }\n\n /**\n * Paths on which adapters serve the OAuth Protected Resource Metadata\n * (empty when `oauth` is not configured). They must be public: no auth middleware.\n */\n get oauthMetadataPaths(): string[] {\n return this.options.oauth ? protectedResourceMetadataPaths(this.options.oauth.resource) : [];\n }\n\n /** The OAuth Protected Resource Metadata document (RFC 9728). */\n async protectedResourceMetadata(): Promise<Record<string, unknown>> {\n const o = this.options.oauth;\n if (!o) throw new Error('mcp-expose: the oauth option is not configured');\n await this.load();\n const scopes = o.scopesSupported ?? [\n ...new Set([...(o.requiredScopes ?? []), ...[...this.tools.values()].flatMap((t) => t.scopes ?? [])]),\n ];\n return {\n resource: o.resource,\n authorization_servers: o.authorizationServers,\n ...(scopes.length ? { scopes_supported: scopes } : {}),\n bearer_methods_supported: ['header'],\n ...(o.resourceName ? { resource_name: o.resourceName } : {}),\n ...(o.resourceDocumentation ? { resource_documentation: o.resourceDocumentation } : {}),\n ...o.metadata,\n };\n }\n\n /** HTTP handler for the metadata paths. Public and CORS-enabled so browser-based clients can read it. */\n async handleMetadataHttp(req: Pick<McpHttpRequest, 'method'>): Promise<McpHttpResponse> {\n const cors = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, OPTIONS' };\n const method = req.method.toUpperCase();\n if (!this.options.oauth) return { status: 404, headers: {} };\n if (method === 'OPTIONS') return { status: 204, headers: { ...cors, 'access-control-allow-headers': '*' } };\n if (method !== 'GET' && method !== 'HEAD') return { status: 405, headers: { allow: 'GET, OPTIONS' } };\n const body = JSON.stringify(await this.protectedResourceMetadata());\n return {\n status: 200,\n headers: { ...cors, 'content-type': 'application/json', 'cache-control': 'public, max-age=3600' },\n body: method === 'HEAD' ? undefined : body,\n };\n }\n\n /**\n * Framework-neutral Streamable HTTP handler. Adapters convert their request\n * into McpHttpRequest, call this, and write the McpHttpResponse back.\n */\n async handleHttp(req: McpHttpRequest, ctx: ToolContext): Promise<McpHttpResponse> {\n const json = { 'content-type': 'application/json' };\n if (!this.isOriginAllowed(req.headers.origin)) {\n return { status: 403, headers: json, body: JSON.stringify(fail(null, INVALID_REQUEST, 'Origin not allowed')) };\n }\n const oauth = this.options.oauth;\n if (oauth) {\n const outcome = await authenticate(oauth, req.headers);\n if (!outcome.ok) return authError(outcome);\n ctx = { ...ctx, auth: outcome.auth };\n }\n if (req.method.toUpperCase() !== 'POST') {\n // Stateless server: no standalone SSE stream and no sessions to delete.\n return { status: 405, headers: { allow: 'POST' } };\n }\n let body = req.body;\n if (typeof body === 'string' || body instanceof Uint8Array) {\n try {\n body = JSON.parse(typeof body === 'string' ? body : new TextDecoder().decode(body));\n } catch {\n return { status: 400, headers: json, body: JSON.stringify(fail(null, PARSE_ERROR, 'Parse error')) };\n }\n }\n if (oauth) {\n // Per-tool scopes: answer 403 so the client can ask the user for more access (step-up).\n await this.load();\n const calls = (Array.isArray(body) ? body : [body]) as Partial<JsonRpcRequest>[];\n for (const m of calls) {\n if (m?.method !== 'tools/call') continue;\n const tool = this.tools.get(m.params?.name as string);\n const missing = missingScopes(ctx.auth, tool?.scopes);\n if (missing.length) {\n // Include the scopes already granted, so re-authorizing never drops access the user gave before.\n const scope = [\n ...new Set([...(ctx.auth?.scopes ?? []), ...(oauth.requiredScopes ?? []), ...(tool?.scopes ?? [])]),\n ];\n return authError(\n deny(oauth, 403, 'insufficient_scope', `Tool \"${tool!.name}\" needs scope: ${missing.join(' ')}`, scope),\n );\n }\n }\n }\n const response = await this.handleMessage(body, ctx);\n if (response === null) return { status: 202, headers: {} };\n return { status: 200, headers: json, body: JSON.stringify(response) };\n }\n}\n\nfunction authError(o: { status: number; challenge: string; error: string; description: string }): McpHttpResponse {\n return {\n status: o.status,\n headers: { 'content-type': 'application/json', 'www-authenticate': o.challenge },\n body: JSON.stringify({ error: o.error, error_description: o.description }),\n };\n}\n","import type { JsonSchema, McpToolDefinition, SchemaLike } from './types.js';\n\ninterface StandardSchemaV1 {\n '~standard': {\n validate?: (value: unknown) => unknown;\n jsonSchema?: { input?: (opts: { target: string }) => unknown };\n };\n}\n\nfunction isStandard(s: unknown): s is StandardSchemaV1 {\n return typeof s === 'object' && s !== null && '~standard' in s;\n}\n\n/** Convert any supported schema flavour into a plain JSON Schema object. */\nexport function toJsonSchema(schema: SchemaLike | undefined): JsonSchema | undefined {\n if (schema === undefined || schema === null) return undefined;\n let out: unknown;\n if (isStandard(schema) && typeof schema['~standard'].jsonSchema?.input === 'function') {\n out = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' });\n } else if (typeof (schema as { toJSONSchema?: unknown }).toJSONSchema === 'function') {\n out = (schema as { toJSONSchema(): unknown }).toJSONSchema();\n } else if (isStandard(schema)) {\n throw new Error(\n 'mcp-expose: this schema library does not support JSON Schema export. Pass a plain JSON Schema instead.',\n );\n } else {\n out = schema;\n }\n const { $schema: _ignored, ...rest } = out as JsonSchema;\n return rest;\n}\n\n/** Build a validator from a Standard Schema, if the input is one. */\nexport function toValidator(schema: SchemaLike | undefined): McpToolDefinition['validate'] {\n if (!isStandard(schema) || typeof schema['~standard'].validate !== 'function') return undefined;\n const validate = schema['~standard'].validate;\n return async (value) => {\n const result = (await validate(value)) as {\n value?: unknown;\n issues?: { message: string; path?: (PropertyKey | { key: PropertyKey })[] }[];\n };\n if (!result.issues) return { ok: true, value: result.value };\n const message = result.issues\n .map((i) => {\n const path = (i.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return path ? `${path}: ${i.message}` : i.message;\n })\n .join('; ');\n return { ok: false, message };\n };\n}\n\n/** Very small structural check used when no Standard Schema validator exists. */\nexport function checkRequired(schema: JsonSchema, args: Record<string, unknown>): string | undefined {\n const missing = (schema.required ?? []).filter((k) => args[k] === undefined);\n return missing.length ? `Missing required argument(s): ${missing.join(', ')}` : undefined;\n}\n","import { checkRequired, toJsonSchema, toValidator } from './schema.js';\nimport type {\n Dispatcher,\n JsonSchema,\n McpServerOptions,\n McpToolDefinition,\n RouteResponse,\n RouteSpec,\n RouteToolOptions,\n ToolAnnotations,\n ToolContext,\n ToolResult,\n} from './types.js';\n\nexport const DEFAULT_FORWARD_HEADERS = ['authorization', 'cookie', 'x-api-key', 'accept-language'];\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);\nconst PARAM_RE = /:([A-Za-z0-9_]+)\\??|\\{([A-Za-z0-9_]+)\\}/g;\n\n/** Names of the path parameters in a route path (`/a/:id/{slug}` -> ['id', 'slug']). */\nexport function pathParams(path: string): string[] {\n return [...path.matchAll(PARAM_RE)].map((m) => (m[1] ?? m[2]) as string);\n}\n\n/**\n * Encode one path-parameter value. Rejects empty, `.` and `..` values: after URL\n * normalisation they would change which route is called (e.g. `/orders/../admin`),\n * letting an agent reach routes that were never exposed as tools.\n */\nfunction encodeSegment(name: string, value: unknown): string {\n const raw = String(value);\n if (raw === '' || raw === '.' || raw === '..') {\n throw new Error(`Invalid value for path parameter \"${name}\": ${JSON.stringify(raw)}`);\n }\n return encodeURIComponent(raw);\n}\n\n/** Replace path placeholders with URL-encoded values. Missing optional params drop their segment. */\nexport function interpolatePath(path: string, values: Record<string, unknown>): string {\n return path\n .replace(/\\/:([A-Za-z0-9_]+)\\?/g, (_, k: string) =>\n values[k] === undefined ? '' : `/${encodeSegment(k, values[k])}`,\n )\n .replace(PARAM_RE, (_, a?: string, b?: string) => {\n const k = (a ?? b) as string;\n return encodeSegment(k, values[k]);\n });\n}\n\n/** Join path segments, normalising slashes. */\nexport function joinPaths(...parts: (string | undefined)[]): string {\n const joined = parts\n .filter((p): p is string => !!p && p !== '/')\n .map((p) => p.replace(/^\\/+|\\/+$/g, ''))\n .filter(Boolean)\n .join('/');\n return `/${joined}`;\n}\n\n/** `GET /users/:id/orders` -> `get_users_by_id_orders` */\nexport function toolNameFromRoute(method: string, path: string): string {\n const segments = path\n .split('/')\n .filter(Boolean)\n .map((s) => {\n const m = /^(?::([A-Za-z0-9_]+)\\??|\\{([A-Za-z0-9_]+)\\})$/.exec(s);\n return m ? `by_${m[1] ?? m[2]}` : s;\n });\n return sanitizeToolName([method.toLowerCase(), ...segments].join('_'));\n}\n\nexport function sanitizeToolName(name: string): string {\n return name\n .replace(/[^A-Za-z0-9_-]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n .slice(0, 64);\n}\n\nfunction defaultAnnotations(method: string): ToolAnnotations {\n switch (method) {\n case 'GET':\n case 'HEAD':\n return { readOnlyHint: true, openWorldHint: false };\n case 'DELETE':\n return { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false };\n case 'PUT':\n return { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };\n default:\n return { readOnlyHint: false, destructiveHint: false, openWorldHint: false };\n }\n}\n\ninterface ArgMapping {\n params: string[];\n query: Set<string>;\n body: Set<string>;\n /** Body schema is not an object: the whole body is passed under the `body` key. */\n wholeBody: boolean;\n bodyMethod: boolean;\n}\n\n/**\n * Build the flat input schema an agent sees, and remember which argument goes\n * to the path, query string or body when the tool is called.\n */\nexport function buildInputSchema(\n route: RouteSpec,\n opts: RouteToolOptions,\n): { schema: JsonSchema; mapping: ArgMapping } {\n const method = route.method.toUpperCase();\n const params = pathParams(route.path);\n const mapping: ArgMapping = {\n params,\n query: new Set(),\n body: new Set(),\n wholeBody: false,\n bodyMethod: BODY_METHODS.has(method),\n };\n\n if (opts.input) {\n const schema = toJsonSchema(opts.input) as JsonSchema;\n return { schema: { type: 'object', ...schema }, mapping };\n }\n\n const properties: Record<string, JsonSchema> = {};\n const required = new Set<string>();\n\n const paramSchema = toJsonSchema(opts.params);\n for (const p of params) {\n properties[p] = paramSchema?.properties?.[p] ?? { type: 'string', description: `Path parameter \"${p}\"` };\n if (!route.path.includes(`:${p}?`)) required.add(p);\n }\n\n const querySchema = toJsonSchema(opts.query);\n for (const [k, v] of Object.entries(querySchema?.properties ?? {})) {\n properties[k] = v;\n mapping.query.add(k);\n }\n for (const k of querySchema?.required ?? []) required.add(k);\n\n const bodySchema = toJsonSchema(opts.body);\n if (bodySchema) {\n if (bodySchema.properties && (bodySchema.type === undefined || bodySchema.type === 'object')) {\n for (const [k, v] of Object.entries(bodySchema.properties)) {\n properties[k] = v;\n mapping.body.add(k);\n }\n for (const k of bodySchema.required ?? []) required.add(k);\n } else {\n properties.body = bodySchema;\n required.add('body');\n mapping.wholeBody = true;\n }\n }\n\n const schema: JsonSchema = { type: 'object', properties };\n if (required.size) schema.required = [...required];\n return { schema, mapping };\n}\n\nfunction splitArgs(args: Record<string, unknown>, mapping: ArgMapping) {\n const pathValues: Record<string, unknown> = {};\n const query: Record<string, string | string[]> = {};\n let body: Record<string, unknown> | unknown | undefined;\n\n for (const [k, v] of Object.entries(args)) {\n if (v === undefined) continue;\n if (mapping.params.includes(k)) {\n pathValues[k] = v;\n } else if (mapping.wholeBody && k === 'body') {\n body = v;\n } else if (mapping.query.has(k) || (!mapping.body.has(k) && !mapping.bodyMethod)) {\n query[k] = Array.isArray(v) ? v.map(String) : typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v);\n } else {\n body = { ...((body as Record<string, unknown>) ?? {}), [k]: v };\n }\n }\n if (body === undefined && mapping.bodyMethod) body = {};\n return { pathValues, query, body };\n}\n\nexport function responseToResult(res: RouteResponse, maxChars: number): ToolResult {\n let text = res.body;\n if (text.length > maxChars) text = `${text.slice(0, maxChars)}\\n…[truncated ${text.length - maxChars} chars]`;\n const isError = res.status >= 400;\n const result: ToolResult = {\n content: [{ type: 'text', text: isError ? `HTTP ${res.status}\\n${text}` : text || `HTTP ${res.status}` }],\n };\n if (isError) {\n result.isError = true;\n return result;\n }\n if ((res.headers['content-type'] ?? '').includes('json') && text === res.body) {\n try {\n const parsed = JSON.parse(res.body);\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) result.structuredContent = parsed;\n } catch {\n /* not JSON after all */\n }\n }\n return result;\n}\n\nexport function pickForwardHeaders(ctx: ToolContext, names: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of names) {\n const v = ctx.headers[name.toLowerCase()];\n if (v !== undefined) out[name.toLowerCase()] = v;\n }\n return out;\n}\n\n/**\n * Turn an HTTP route + options into an MCP tool whose handler calls the route\n * through `dispatch`, so auth guards, validation and rate limits all still apply.\n */\nexport function createRouteTool(\n route: RouteSpec,\n opts: RouteToolOptions,\n dispatch: Dispatcher,\n serverOpts: Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars'> = {},\n): McpToolDefinition {\n const method = route.method.toUpperCase();\n const name = sanitizeToolName(opts.name ?? toolNameFromRoute(method, route.path));\n const { schema, mapping } = buildInputSchema(route, opts);\n const forward = serverOpts.forwardHeaders ?? DEFAULT_FORWARD_HEADERS;\n const maxChars = serverOpts.maxResponseChars ?? 100_000;\n\n return {\n name,\n title: opts.title,\n description: opts.description ?? `${method} ${route.path}`,\n inputSchema: schema,\n annotations: { ...defaultAnnotations(method), ...opts.annotations },\n scopes: opts.scopes,\n validate: toValidator(opts.input),\n async handler(args, ctx) {\n const missing = opts.input ? undefined : checkRequired(schema, args);\n if (missing) return { isError: true, content: [{ type: 'text', text: missing }] };\n\n const { pathValues, query, body } = splitArgs(args, mapping);\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...pickForwardHeaders(ctx, forward),\n ...opts.headers,\n 'x-mcp-tool': name,\n };\n if (ctx.clientIp) headers['x-forwarded-for'] = ctx.clientIp;\n if (body !== undefined) headers['content-type'] = 'application/json';\n\n let path: string;\n try {\n path = interpolatePath(route.path, pathValues);\n } catch (err) {\n return { isError: true, content: [{ type: 'text', text: (err as Error).message }] };\n }\n const res = await dispatch({ method, path, query, body, headers }, ctx);\n return responseToResult(res, maxChars);\n },\n };\n}\n","import type { Dispatcher, RouteRequest, ToolContext } from './types.js';\n\nexport function buildUrl(base: string, req: Pick<RouteRequest, 'path' | 'query'>): string {\n const url = new URL(base.replace(/\\/+$/, '') + req.path);\n for (const [k, v] of Object.entries(req.query)) {\n for (const item of Array.isArray(v) ? v : [v]) url.searchParams.append(k, item);\n }\n return url.toString();\n}\n\nexport interface FetchDispatcherOptions {\n /**\n * Base URL of the API, e.g. `http://127.0.0.1:3000` or `https://api.example.com/v1`.\n * A function lets adapters resolve it per call (e.g. from the local port).\n */\n baseUrl: string | ((ctx: ToolContext) => string);\n /** Custom fetch implementation. Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout in ms. @default 30_000 */\n timeoutMs?: number;\n}\n\n/**\n * Dispatches tool calls as real HTTP requests. Used for loopback calls into the\n * host app (Express, Koa, NestJS) and for standalone gateways in front of any API.\n */\nexport function createFetchDispatcher(opts: FetchDispatcherOptions): Dispatcher {\n const doFetch = opts.fetch ?? fetch;\n return async (req, ctx) => {\n const base = typeof opts.baseUrl === 'function' ? opts.baseUrl(ctx) : opts.baseUrl;\n const res = await doFetch(buildUrl(base, req), {\n method: req.method,\n headers: req.headers,\n body:\n req.body === undefined || req.method === 'GET' || req.method === 'HEAD' ? undefined : JSON.stringify(req.body),\n signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),\n });\n const headers: Record<string, string> = {};\n res.headers.forEach((v, k) => (headers[k] = v));\n return { status: res.status, headers, body: await res.text() };\n };\n}\n","import { createRouteTool } from './route-tool.js';\nimport { toJsonSchema, toValidator } from './schema.js';\nimport type {\n Dispatcher,\n JsonSchema,\n McpServerOptions,\n McpToolDefinition,\n RouteToolOptions,\n SchemaLike,\n ToolAnnotations,\n ToolContext,\n ToolResult,\n} from './types.js';\n\nexport interface DefineToolOptions {\n name: string;\n title?: string;\n description: string;\n input?: SchemaLike;\n annotations?: ToolAnnotations;\n /** OAuth scopes needed to call this tool (when the `oauth` option is enabled). */\n scopes?: string[];\n /** Return a string, any JSON value, or a full ToolResult. */\n handler: (args: any, ctx: ToolContext) => unknown;\n}\n\n/** Define a code-only tool that is not backed by an HTTP route. */\nexport function defineTool(opts: DefineToolOptions): McpToolDefinition {\n return {\n name: opts.name,\n title: opts.title,\n description: opts.description,\n inputSchema: { type: 'object', ...(toJsonSchema(opts.input) ?? { properties: {} }) },\n annotations: opts.annotations,\n scopes: opts.scopes,\n validate: toValidator(opts.input),\n async handler(args, ctx) {\n return toToolResult(await opts.handler(args, ctx));\n },\n };\n}\n\nexport function toToolResult(value: unknown): ToolResult {\n if (value && typeof value === 'object' && Array.isArray((value as ToolResult).content)) return value as ToolResult;\n if (typeof value === 'string') return { content: [{ type: 'text', text: value }] };\n const text = JSON.stringify(value ?? null);\n const result: ToolResult = { content: [{ type: 'text', text }] };\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n result.structuredContent = value as Record<string, unknown>;\n }\n return result;\n}\n\ninterface OpenApiOperation {\n operationId?: string;\n summary?: string;\n description?: string;\n parameters?: { name: string; in: string; required?: boolean; description?: string; schema?: JsonSchema }[];\n requestBody?: { content?: Record<string, { schema?: JsonSchema }> };\n 'x-mcp'?: boolean | RouteToolOptions;\n}\n\nexport interface FromOpenApiOptions {\n /**\n * Which operations to expose. Defaults to operations marked with `x-mcp: true`\n * (or an `x-mcp` options object). Pass `() => true` to expose everything.\n */\n include?: (op: { method: string; path: string; operation: OpenApiOperation }) => boolean;\n}\n\n/**\n * Build tools from an OpenAPI 3.x document. Works with any framework that can\n * emit OpenAPI (e.g. @nestjs/swagger, @fastify/swagger, tsoa, hono-openapi).\n * `$ref`s are not resolved, so pass a dereferenced document.\n */\nexport function toolsFromOpenApi(\n doc: { paths?: Record<string, Record<string, OpenApiOperation>> },\n dispatch: Dispatcher,\n opts: FromOpenApiOptions & Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars'> = {},\n): McpToolDefinition[] {\n const include = opts.include ?? (({ operation }) => !!operation['x-mcp']);\n const methods = ['get', 'post', 'put', 'patch', 'delete'];\n const tools: McpToolDefinition[] = [];\n\n for (const [path, item] of Object.entries(doc.paths ?? {})) {\n for (const method of methods) {\n const operation = item[method];\n if (!operation || !include({ method, path, operation })) continue;\n const extra = typeof operation['x-mcp'] === 'object' ? operation['x-mcp'] : {};\n\n const query: JsonSchema = { type: 'object', properties: {}, required: [] };\n const params: JsonSchema = { type: 'object', properties: {} };\n for (const p of operation.parameters ?? []) {\n const s = { ...(p.schema ?? { type: 'string' }), ...(p.description ? { description: p.description } : {}) };\n if (p.in === 'query') {\n query.properties![p.name] = s;\n if (p.required) query.required!.push(p.name);\n } else if (p.in === 'path') params.properties![p.name] = s;\n }\n const body = operation.requestBody?.content?.['application/json']?.schema;\n\n tools.push(\n createRouteTool(\n { method, path },\n {\n name: operation.operationId,\n description: operation.description ?? operation.summary,\n params,\n query,\n body,\n ...extra,\n },\n dispatch,\n opts,\n ),\n );\n }\n }\n return tools;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;ACiEO,IAAMA,gCAAgC;AAOtC,SAASC,+BAA+BC,UAAgB;AAC7D,QAAMC,WAAW,IAAIC,IAAIF,QAAAA,EAAUC,SAASE,QAAQ,QAAQ,EAAA;AAC5D,SAAOF,WACH;IAACH,gCAAgCG;IAAUH;MAC3C;IAACA;;AACP;AALgBC;AAQT,SAASK,6BAA6BJ,UAAgB;AAC3D,SAAO,IAAIE,IAAIH,+BAA+BC,QAAAA,EAAU,CAAA,GAAcA,QAAAA,EAAUK;AAClF;AAFgBD;AAIT,SAASE,qBAAqBC,GAAe;AAClD,MAAIC;AACJ,MAAI;AACFA,UAAM,IAAIN,IAAIK,EAAEP,QAAQ;EAC1B,QAAQ;AACN,UAAM,IAAIS,MAAM,2DAA2DC,KAAKC,UAAUJ,EAAEP,QAAQ,CAAA,EAAG;EACzG;AACA,MAAIQ,IAAII,KAAM,OAAM,IAAIH,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IAAAA,CAAAA;IAGN;EACF;AACA,SAAOgC;AACT;AA5CgBN;","names":["PROTECTED_RESOURCE_WELL_KNOWN","protectedResourceMetadataPaths","resource","pathname","URL","replace","protectedResourceMetadataUrl","href","validateOAuthOptions","o","url","Error","JSON","stringify","hash","authorizationServers","length","verifyToken","quote","v","bearerChallenge","params","parts","error","push","errorDescription","scope","join","bearerToken","headers","m","exec","authorization","authenticate","token","ok","status","description","challenge","requiredScopes","auth","undefined","deny","expiresAt","Date","now","missing","missingScopes","Set","scopes","required","granted","filter","s","has","parseScopes","value","Array","isArray","map","String","split","Boolean","SUPPORTED_PROTOCOL_VERSIONS","LATEST_PROTOCOL_VERSION","PARSE_ERROR","INVALID_REQUEST","METHOD_NOT_FOUND","INVALID_PARAMS","ok","id","result","jsonrpc","fail","code","message","error","McpServer","tools","Map","loaders","options","oauth","validateOAuthOptions","addTool","tool","has","name","Error","set","onLoad","loader","push","listTools","load","values","length","l","handleMessage","ctx","Array","isArray","results","Promise","all","map","m","handleOne","filter","r","msg","method","undefined","params","requested","protocolVersion","includes","capabilities","listChanged","serverInfo","version","instructions","t","title","description","inputSchema","annotations","get","String","callTool","arguments","resources","prompts","args","validate","v","isError","content","type","text","value","handler","err","isOriginAllowed","origin","allowed","allowedOrigins","oauthMetadataPaths","protectedResourceMetadataPaths","resource","protectedResourceMetadata","o","scopes","scopesSupported","Set","requiredScopes","flatMap","authorization_servers","authorizationServers","scopes_supported","bearer_methods_supported","resourceName","resource_name","resourceDocumentation","resource_documentation","metadata","handleMetadataHttp","req","cors","toUpperCase","status","headers","allow","body","JSON","stringify","handleHttp","json","outcome","authenticate","authError","auth","Uint8Array","parse","TextDecoder","decode","calls","missing","missingScopes","scope","deny","join","response","challenge","error_description","isStandard","s","toJsonSchema","schema","undefined","out","jsonSchema","input","target","toJSONSchema","Error","$schema","_ignored","rest","toValidator","validate","value","result","issues","ok","message","map","i","path","p","String","key","join","checkRequired","args","missing","required","filter","k","length","DEFAULT_FORWARD_HEADERS","BODY_METHODS","Set","PARAM_RE","pathParams","path","matchAll","map","m","encodeSegment","name","value","raw","String","Error","JSON","stringify","encodeURIComponent","interpolatePath","values","replace","_","k","undefined","a","b","toolNameFromRoute","method","path","segments","split","filter","Boolean","map","s","m","exec","sanitizeToolName","toLowerCase","join","name","replace","slice","defaultAnnotations","readOnlyHint","openWorldHint","destructiveHint","idempotentHint","buildInputSchema","route","opts","toUpperCase","params","pathParams","mapping","query","Set","body","wholeBody","bodyMethod","BODY_METHODS","has","input","schema","toJsonSchema","type","properties","required","paramSchema","p","description","includes","add","querySchema","k","v","Object","entries","bodySchema","undefined","size","splitArgs","args","pathValues","Array","isArray","String","JSON","stringify","responseToResult","res","maxChars","text","length","isError","status","result","content","headers","parsed","parse","structuredContent","pickForwardHeaders","ctx","names","out","createRouteTool","dispatch","serverOpts","forward","forwardHeaders","DEFAULT_FORWARD_HEADERS","maxResponseChars","title","inputSchema","annotations","scopes","validate","toValidator","handler","missing","checkRequired","accept","clientIp","interpolatePath","err","message","buildUrl","base","req","url","URL","replace","path","k","v","Object","entries","query","item","Array","isArray","searchParams","append","toString","createFetchDispatcher","opts","doFetch","fetch","ctx","baseUrl","res","method","headers","body","undefined","JSON","stringify","signal","AbortSignal","timeout","timeoutMs","forEach","status","text","defineTool","opts","name","title","description","inputSchema","type","toJsonSchema","input","properties","annotations","scopes","validate","toValidator","handler","args","ctx","toToolResult","value","Array","isArray","content","text","JSON","stringify","result","structuredContent","toolsFromOpenApi","doc","dispatch","include","operation","methods","tools","path","item","Object","entries","paths","method","extra","query","required","params","p","parameters","s","schema","in","push","body","requestBody","createRouteTool","operationId","summary"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/core/oauth.ts","../src/core/server.ts","../src/core/result.ts","../src/core/schema.ts","../src/core/route-tool.ts","../src/core/dispatch.ts","../src/core/define.ts"],"sourcesContent":["/**\n * Public API of `mcp-expose` (framework-agnostic core).\n * Framework adapters live in `mcp-expose/<framework>`.\n */\nexport * from './core/types.js';\nexport { McpServer, SUPPORTED_PROTOCOL_VERSIONS, LATEST_PROTOCOL_VERSION } from './core/server.js';\nexport type { McpHttpRequest, McpHttpResponse, JsonRpcResponse } from './core/server.js';\nexport { createRouteTool, DEFAULT_FORWARD_HEADERS } from './core/route-tool.js';\nexport { createFetchDispatcher } from './core/dispatch.js';\nexport type { FetchDispatcherOptions } from './core/dispatch.js';\nexport { defineTool, toolsFromOpenApi, toToolResult } from './core/define.js';\nexport type { DefineToolOptions, FromOpenApiOptions } from './core/define.js';\nexport { toJsonSchema } from './core/schema.js';\nexport {\n bearerChallenge,\n parseScopes,\n protectedResourceMetadataPaths,\n protectedResourceMetadataUrl,\n} from './core/oauth.js';\n","/**\n * OAuth 2.1 support per the MCP authorization spec: the MCP endpoint acts as an\n * OAuth *resource server*. It publishes Protected Resource Metadata (RFC 9728),\n * answers unauthenticated requests with a `WWW-Authenticate` challenge that\n * tells the client where to log in, and checks bearer tokens with a verifier\n * you provide (see `jwtVerifier` / `introspectionVerifier` in `mcp-expose/oauth`).\n *\n * Runtime-agnostic: no `node:*` imports.\n */\n\n/** Who the access token belongs to and what it allows. Available to tools as `ctx.auth`. */\nexport interface AuthInfo {\n /** The raw access token. */\n token: string;\n /** Scopes granted to the token. */\n scopes: string[];\n /** Subject (user id), e.g. the JWT `sub` claim. */\n subject?: string;\n /** OAuth client the token was issued to. */\n clientId?: string;\n /** Expiry, in seconds since the epoch. Expired tokens are rejected. */\n expiresAt?: number;\n /** All claims / introspection fields. */\n claims?: Record<string, unknown>;\n}\n\nexport interface VerifyTokenContext {\n /** The canonical resource URL (`oauth.resource`). Tokens must be issued for it (audience). */\n resource: string;\n /** Lower-cased headers of the MCP request. */\n headers: Record<string, string>;\n}\n\n/**\n * Checks an access token. Return its AuthInfo, or `undefined` / throw when the\n * token is invalid. It MUST check that the token was issued for this server\n * (audience = `ctx.resource`), or tokens meant for other services would be accepted.\n */\nexport type TokenVerifier = (\n token: string,\n ctx: VerifyTokenContext,\n) => AuthInfo | undefined | null | Promise<AuthInfo | undefined | null>;\n\nexport interface OAuthOptions {\n /**\n * Canonical, public URL of the MCP endpoint, e.g. `https://api.example.com/mcp`.\n * Clients request tokens for this resource, and it must match the URL they connect to.\n */\n resource: string;\n /** Issuer URLs of the authorization servers that issue tokens for this server. */\n authorizationServers: string[];\n /** Checks bearer tokens. */\n verifyToken: TokenVerifier;\n /** Scopes every token needs to use the MCP endpoint at all. */\n requiredScopes?: string[];\n /** Scopes advertised in the metadata. @default requiredScopes plus every tool's `scopes` */\n scopesSupported?: string[];\n /** Human-readable name shown by clients. */\n resourceName?: string;\n /** URL of documentation for developers. */\n resourceDocumentation?: string;\n /** Extra fields merged into the Protected Resource Metadata document. */\n metadata?: Record<string, unknown>;\n}\n\nexport const PROTECTED_RESOURCE_WELL_KNOWN = '/.well-known/oauth-protected-resource';\n\n/**\n * Paths the metadata is served on, per RFC 9728: the well-known prefix with the\n * resource path appended (`/.well-known/oauth-protected-resource/mcp`), plus the\n * bare well-known path that older clients fall back to.\n */\nexport function protectedResourceMetadataPaths(resource: string): string[] {\n const pathname = new URL(resource).pathname.replace(/\\/+$/, '');\n return pathname\n ? [PROTECTED_RESOURCE_WELL_KNOWN + pathname, PROTECTED_RESOURCE_WELL_KNOWN]\n : [PROTECTED_RESOURCE_WELL_KNOWN];\n}\n\n/** Absolute URL of the metadata document, used in `WWW-Authenticate`. */\nexport function protectedResourceMetadataUrl(resource: string): string {\n return new URL(protectedResourceMetadataPaths(resource)[0] as string, resource).href;\n}\n\nexport function validateOAuthOptions(o: OAuthOptions): void {\n let url: URL;\n try {\n url = new URL(o.resource);\n } catch {\n throw new Error(`mcp-expose: oauth.resource must be an absolute URL, got ${JSON.stringify(o.resource)}`);\n }\n if (url.hash) throw new Error('mcp-expose: oauth.resource must not contain a fragment');\n if (!o.authorizationServers?.length) throw new Error('mcp-expose: oauth.authorizationServers must not be empty');\n if (typeof o.verifyToken !== 'function') throw new Error('mcp-expose: oauth.verifyToken is required');\n}\n\nconst quote = (v: string) => `\"${v.replace(/[\"\\\\]/g, '\\\\$&')}\"`;\n\n/** Build a `WWW-Authenticate: Bearer ...` challenge (RFC 6750 + RFC 9728). */\nexport function bearerChallenge(\n resource: string,\n params: { error?: string; errorDescription?: string; scope?: string[] } = {},\n): string {\n const parts: string[] = [];\n if (params.error) parts.push(`error=${quote(params.error)}`);\n if (params.errorDescription) parts.push(`error_description=${quote(params.errorDescription)}`);\n if (params.scope?.length) parts.push(`scope=${quote(params.scope.join(' '))}`);\n parts.push(`resource_metadata=${quote(protectedResourceMetadataUrl(resource))}`);\n return `Bearer ${parts.join(', ')}`;\n}\n\n/** Extract the token from `Authorization: Bearer <token>`. Tokens in the query string are never accepted. */\nexport function bearerToken(headers: Record<string, string>): string | undefined {\n const m = /^Bearer[ ]+([^\\s,]+)\\s*$/i.exec(headers.authorization ?? '');\n return m?.[1];\n}\n\nexport type AuthOutcome =\n | { ok: true; auth: AuthInfo }\n | { ok: false; status: 401 | 403; challenge: string; error: string; description: string };\n\n/** Authenticate one MCP request. */\nexport async function authenticate(o: OAuthOptions, headers: Record<string, string>): Promise<AuthOutcome> {\n const token = bearerToken(headers);\n if (!token) {\n // No credentials: a bare challenge pointing at the metadata starts the client's login flow.\n return {\n ok: false,\n status: 401,\n error: 'unauthorized',\n description: 'Authorization required',\n challenge: bearerChallenge(o.resource, { scope: o.requiredScopes }),\n };\n }\n\n let auth: AuthInfo | undefined | null;\n try {\n auth = await o.verifyToken(token, { resource: o.resource, headers });\n } catch {\n auth = undefined;\n }\n if (!auth) return deny(o, 401, 'invalid_token', 'The access token is invalid');\n if (auth.expiresAt !== undefined && auth.expiresAt * 1000 <= Date.now()) {\n return deny(o, 401, 'invalid_token', 'The access token has expired');\n }\n const missing = missingScopes(auth, o.requiredScopes);\n if (missing.length) {\n // Keep the scopes already granted in the challenge, so re-authorizing never drops access.\n const scope = [...new Set([...(auth.scopes ?? []), ...(o.requiredScopes ?? [])])];\n return deny(o, 403, 'insufficient_scope', `Missing scope: ${missing.join(' ')}`, scope);\n }\n return { ok: true, auth: { ...auth, scopes: auth.scopes ?? [] } };\n}\n\n/** A failed AuthOutcome with an RFC 6750 error challenge. */\nexport function deny(\n o: OAuthOptions,\n status: 401 | 403,\n error: string,\n description: string,\n scope?: string[],\n): AuthOutcome & { ok: false } {\n return {\n ok: false,\n status,\n error,\n description,\n challenge: bearerChallenge(o.resource, { error, errorDescription: description, scope }),\n };\n}\n\nexport function missingScopes(auth: AuthInfo | undefined, required: string[] | undefined): string[] {\n if (!required?.length) return [];\n const granted = new Set(auth?.scopes ?? []);\n return required.filter((s) => !granted.has(s));\n}\n\n/** Parse a space-separated `scope` string or an array of scopes. */\nexport function parseScopes(value: unknown): string[] {\n if (Array.isArray(value)) return value.map(String);\n if (typeof value === 'string') return value.split(' ').filter(Boolean);\n return [];\n}\n","import { authenticate, deny, missingScopes, protectedResourceMetadataPaths, validateOAuthOptions } from './oauth.js';\nimport type { McpServerOptions, McpToolDefinition, ToolContext, ToolResult } from './types.js';\n\nexport const SUPPORTED_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];\nexport const LATEST_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0] as string;\n\ntype JsonRpcId = string | number | null;\ninterface JsonRpcRequest {\n jsonrpc: '2.0';\n id?: JsonRpcId;\n method: string;\n params?: Record<string, unknown>;\n}\nexport interface JsonRpcResponse {\n jsonrpc: '2.0';\n id: JsonRpcId;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nconst PARSE_ERROR = -32700;\nconst INVALID_REQUEST = -32600;\nconst METHOD_NOT_FOUND = -32601;\nconst INVALID_PARAMS = -32602;\n\nconst ok = (id: JsonRpcId, result: unknown): JsonRpcResponse => ({ jsonrpc: '2.0', id, result });\nconst fail = (id: JsonRpcId, code: number, message: string): JsonRpcResponse => ({\n jsonrpc: '2.0',\n id,\n error: { code, message },\n});\n\n/** Minimal HTTP request/response shapes, so each adapter can bridge its own framework. */\nexport interface McpHttpRequest {\n method: string;\n headers: Record<string, string>;\n /** Parsed JSON body, or the raw string. */\n body: unknown;\n}\nexport interface McpHttpResponse {\n status: number;\n headers: Record<string, string>;\n body?: string;\n}\n\n/**\n * A stateless MCP server speaking the Streamable HTTP transport (JSON responses).\n * Holds the tool registry and answers JSON-RPC messages.\n */\nexport class McpServer {\n private readonly tools = new Map<string, McpToolDefinition>();\n private loaders: (() => void | Promise<void>)[] = [];\n\n constructor(readonly options: McpServerOptions) {\n if (options.oauth) validateOAuthOptions(options.oauth);\n }\n\n /** Register a tool. Throws on duplicate names. */\n addTool(tool: McpToolDefinition): this {\n if (this.tools.has(tool.name)) {\n throw new Error(`mcp-expose: duplicate tool name \"${tool.name}\". Set an explicit \\`name\\`.`);\n }\n this.tools.set(tool.name, tool);\n return this;\n }\n\n /** Register a function that adds tools lazily, right before the first MCP request is served. */\n onLoad(loader: () => void | Promise<void>): this {\n this.loaders.push(loader);\n return this;\n }\n\n async listTools(): Promise<McpToolDefinition[]> {\n await this.load();\n return [...this.tools.values()];\n }\n\n private async load() {\n if (!this.loaders.length) return;\n const loaders = this.loaders;\n this.loaders = [];\n for (const l of loaders) await l();\n }\n\n /** Handle one JSON-RPC message (or a batch). Returns null when no response is due. */\n async handleMessage(message: unknown, ctx: ToolContext): Promise<JsonRpcResponse | JsonRpcResponse[] | null> {\n if (Array.isArray(message)) {\n const results = (await Promise.all(message.map((m) => this.handleOne(m, ctx)))).filter(\n (r): r is JsonRpcResponse => r !== null,\n );\n return results.length ? results : null;\n }\n return this.handleOne(message, ctx);\n }\n\n private async handleOne(message: unknown, ctx: ToolContext): Promise<JsonRpcResponse | null> {\n const msg = message as Partial<JsonRpcRequest>;\n if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0') {\n return fail(null, INVALID_REQUEST, 'Invalid JSON-RPC message');\n }\n // Responses from the client or notifications: acknowledge, no reply.\n if (typeof msg.method !== 'string' || msg.id === undefined) return null;\n const id = msg.id;\n const params = msg.params ?? {};\n\n await this.load();\n switch (msg.method) {\n case 'initialize': {\n const requested = params.protocolVersion as string | undefined;\n const protocolVersion =\n requested && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;\n return ok(id, {\n protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: { name: this.options.name, version: this.options.version ?? '1.0.0' },\n ...(this.options.instructions ? { instructions: this.options.instructions } : {}),\n });\n }\n case 'ping':\n return ok(id, {});\n case 'tools/list':\n return ok(id, {\n tools: [...this.tools.values()].map((t) => ({\n name: t.name,\n ...(t.title ? { title: t.title } : {}),\n description: t.description,\n inputSchema: t.inputSchema,\n ...(t.annotations ? { annotations: t.annotations } : {}),\n })),\n });\n case 'tools/call': {\n const tool = this.tools.get(params.name as string);\n if (!tool) return fail(id, INVALID_PARAMS, `Unknown tool: ${String(params.name)}`);\n return ok(id, await this.callTool(tool, (params.arguments ?? {}) as Record<string, unknown>, ctx));\n }\n case 'resources/list':\n return ok(id, { resources: [] });\n case 'prompts/list':\n return ok(id, { prompts: [] });\n default:\n return fail(id, METHOD_NOT_FOUND, `Method not found: ${msg.method}`);\n }\n }\n\n private async callTool(\n tool: McpToolDefinition,\n args: Record<string, unknown>,\n ctx: ToolContext,\n ): Promise<ToolResult> {\n try {\n if (tool.validate) {\n const v = await tool.validate(args);\n if (!v.ok) return { isError: true, content: [{ type: 'text', text: `Invalid arguments: ${v.message}` }] };\n args = v.value as Record<string, unknown>;\n }\n return await tool.handler(args, ctx);\n } catch (err) {\n // Tool failures are reported in-band so the model can react to them.\n return { isError: true, content: [{ type: 'text', text: `Tool error: ${(err as Error).message}` }] };\n }\n }\n\n /** Check the Origin header (DNS rebinding protection). */\n isOriginAllowed(origin: string | undefined): boolean {\n if (!origin) return true;\n const allowed = this.options.allowedOrigins;\n if (allowed === '*') return true;\n return (allowed ?? []).includes(origin);\n }\n\n /**\n * Paths on which adapters serve the OAuth Protected Resource Metadata\n * (empty when `oauth` is not configured). They must be public: no auth middleware.\n */\n get oauthMetadataPaths(): string[] {\n return this.options.oauth ? protectedResourceMetadataPaths(this.options.oauth.resource) : [];\n }\n\n /** The OAuth Protected Resource Metadata document (RFC 9728). */\n async protectedResourceMetadata(): Promise<Record<string, unknown>> {\n const o = this.options.oauth;\n if (!o) throw new Error('mcp-expose: the oauth option is not configured');\n await this.load();\n const scopes = o.scopesSupported ?? [\n ...new Set([...(o.requiredScopes ?? []), ...[...this.tools.values()].flatMap((t) => t.scopes ?? [])]),\n ];\n return {\n resource: o.resource,\n authorization_servers: o.authorizationServers,\n ...(scopes.length ? { scopes_supported: scopes } : {}),\n bearer_methods_supported: ['header'],\n ...(o.resourceName ? { resource_name: o.resourceName } : {}),\n ...(o.resourceDocumentation ? { resource_documentation: o.resourceDocumentation } : {}),\n ...o.metadata,\n };\n }\n\n /** HTTP handler for the metadata paths. Public and CORS-enabled so browser-based clients can read it. */\n async handleMetadataHttp(req: Pick<McpHttpRequest, 'method'>): Promise<McpHttpResponse> {\n const cors = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, OPTIONS' };\n const method = req.method.toUpperCase();\n if (!this.options.oauth) return { status: 404, headers: {} };\n if (method === 'OPTIONS') return { status: 204, headers: { ...cors, 'access-control-allow-headers': '*' } };\n if (method !== 'GET' && method !== 'HEAD') return { status: 405, headers: { allow: 'GET, OPTIONS' } };\n const body = JSON.stringify(await this.protectedResourceMetadata());\n return {\n status: 200,\n headers: { ...cors, 'content-type': 'application/json', 'cache-control': 'public, max-age=3600' },\n body: method === 'HEAD' ? undefined : body,\n };\n }\n\n /**\n * Framework-neutral Streamable HTTP handler. Adapters convert their request\n * into McpHttpRequest, call this, and write the McpHttpResponse back.\n */\n async handleHttp(req: McpHttpRequest, ctx: ToolContext): Promise<McpHttpResponse> {\n const json = { 'content-type': 'application/json' };\n if (!this.isOriginAllowed(req.headers.origin)) {\n return { status: 403, headers: json, body: JSON.stringify(fail(null, INVALID_REQUEST, 'Origin not allowed')) };\n }\n const oauth = this.options.oauth;\n if (oauth) {\n const outcome = await authenticate(oauth, req.headers);\n if (!outcome.ok) return authError(outcome);\n ctx = { ...ctx, auth: outcome.auth };\n }\n if (req.method.toUpperCase() !== 'POST') {\n // Stateless server: no standalone SSE stream and no sessions to delete.\n return { status: 405, headers: { allow: 'POST' } };\n }\n let body = req.body;\n if (typeof body === 'string' || body instanceof Uint8Array) {\n try {\n body = JSON.parse(typeof body === 'string' ? body : new TextDecoder().decode(body));\n } catch {\n return { status: 400, headers: json, body: JSON.stringify(fail(null, PARSE_ERROR, 'Parse error')) };\n }\n }\n if (oauth) {\n // Per-tool scopes: answer 403 so the client can ask the user for more access (step-up).\n await this.load();\n const calls = (Array.isArray(body) ? body : [body]) as Partial<JsonRpcRequest>[];\n for (const m of calls) {\n if (m?.method !== 'tools/call') continue;\n const tool = this.tools.get(m.params?.name as string);\n const missing = missingScopes(ctx.auth, tool?.scopes);\n if (missing.length) {\n // Include the scopes already granted, so re-authorizing never drops access the user gave before.\n const scope = [\n ...new Set([...(ctx.auth?.scopes ?? []), ...(oauth.requiredScopes ?? []), ...(tool?.scopes ?? [])]),\n ];\n return authError(\n deny(oauth, 403, 'insufficient_scope', `Tool \"${tool!.name}\" needs scope: ${missing.join(' ')}`, scope),\n );\n }\n }\n }\n const response = await this.handleMessage(body, ctx);\n if (response === null) return { status: 202, headers: {} };\n return { status: 200, headers: json, body: JSON.stringify(response) };\n }\n}\n\nfunction authError(o: { status: number; challenge: string; error: string; description: string }): McpHttpResponse {\n return {\n status: o.status,\n headers: { 'content-type': 'application/json', 'www-authenticate': o.challenge },\n body: JSON.stringify({ error: o.error, error_description: o.description }),\n };\n}\n","import type { ToolResult } from './types.js';\n\n/** A ToolResult: `{ content: [{ type: 'text', ... }, ...] }`. Plain data with a `content` array is not one. */\nexport function isToolResult(value: unknown): value is ToolResult {\n const content = (value as ToolResult | undefined)?.content;\n return (\n !!value &&\n typeof value === 'object' &&\n Array.isArray(content) &&\n content.length > 0 &&\n content.every((c) => !!c && typeof c === 'object' && typeof (c as { type?: unknown }).type === 'string')\n );\n}\n\n/** Turn a handler's return value (string, JSON value or ToolResult) into a ToolResult. */\nexport function toToolResult(value: unknown): ToolResult {\n if (isToolResult(value)) return value;\n if (typeof value === 'string') return { content: [{ type: 'text', text: value }] };\n const text = JSON.stringify(value ?? null);\n const result: ToolResult = { content: [{ type: 'text', text }] };\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n result.structuredContent = value as Record<string, unknown>;\n }\n return result;\n}\n","import type { JsonSchema, McpToolDefinition, SchemaLike } from './types.js';\n\ninterface StandardSchemaV1 {\n '~standard': {\n validate?: (value: unknown) => unknown;\n jsonSchema?: { input?: (opts: { target: string }) => unknown };\n };\n}\n\nfunction isStandard(s: unknown): s is StandardSchemaV1 {\n return typeof s === 'object' && s !== null && '~standard' in s;\n}\n\n/** Convert any supported schema flavour into a plain JSON Schema object. */\nexport function toJsonSchema(schema: SchemaLike | undefined): JsonSchema | undefined {\n if (schema === undefined || schema === null) return undefined;\n let out: unknown;\n if (isStandard(schema) && typeof schema['~standard'].jsonSchema?.input === 'function') {\n out = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' });\n } else if (typeof (schema as { toJSONSchema?: unknown }).toJSONSchema === 'function') {\n out = (schema as { toJSONSchema(): unknown }).toJSONSchema();\n } else if (isStandard(schema)) {\n throw new Error(\n 'mcp-expose: this schema library does not support JSON Schema export. Pass a plain JSON Schema instead.',\n );\n } else {\n out = schema;\n }\n const { $schema: _ignored, ...rest } = out as JsonSchema;\n return rest;\n}\n\n/** Build a validator from a Standard Schema, if the input is one. */\nexport function toValidator(schema: SchemaLike | undefined): McpToolDefinition['validate'] {\n if (!isStandard(schema) || typeof schema['~standard'].validate !== 'function') return undefined;\n const validate = schema['~standard'].validate;\n return async (value) => {\n const result = (await validate(value)) as {\n value?: unknown;\n issues?: { message: string; path?: (PropertyKey | { key: PropertyKey })[] }[];\n };\n if (!result.issues) return { ok: true, value: result.value };\n const message = result.issues\n .map((i) => {\n const path = (i.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return path ? `${path}: ${i.message}` : i.message;\n })\n .join('; ');\n return { ok: false, message };\n };\n}\n\n/** Very small structural check used when no Standard Schema validator exists. */\nexport function checkRequired(schema: JsonSchema, args: Record<string, unknown>): string | undefined {\n const missing = (schema.required ?? []).filter((k) => args[k] === undefined);\n return missing.length ? `Missing required argument(s): ${missing.join(', ')}` : undefined;\n}\n","import { isToolResult, toToolResult } from './result.js';\nimport { checkRequired, toJsonSchema, toValidator } from './schema.js';\nimport type {\n Dispatcher,\n JsonSchema,\n McpServerOptions,\n McpToolDefinition,\n ResponseTransformContext,\n RouteRequest,\n RouteResponse,\n RouteToolResponse,\n RouteSpec,\n RouteToolOptions,\n ToolAnnotations,\n ToolContext,\n ToolResult,\n} from './types.js';\n\nexport const DEFAULT_FORWARD_HEADERS = ['authorization', 'cookie', 'x-api-key', 'accept-language'];\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);\nconst PARAM_RE = /:([A-Za-z0-9_]+)\\??|\\{([A-Za-z0-9_]+)\\}/g;\n\n/** Names of the path parameters in a route path (`/a/:id/{slug}` -> ['id', 'slug']). */\nexport function pathParams(path: string): string[] {\n return [...path.matchAll(PARAM_RE)].map((m) => (m[1] ?? m[2]) as string);\n}\n\n/**\n * Encode one path-parameter value. Rejects empty, `.` and `..` values: after URL\n * normalisation they would change which route is called (e.g. `/orders/../admin`),\n * letting an agent reach routes that were never exposed as tools.\n */\nfunction encodeSegment(name: string, value: unknown): string {\n const raw = String(value);\n if (raw === '' || raw === '.' || raw === '..') {\n throw new Error(`Invalid value for path parameter \"${name}\": ${JSON.stringify(raw)}`);\n }\n return encodeURIComponent(raw);\n}\n\n/** Replace path placeholders with URL-encoded values. Missing optional params drop their segment. */\nexport function interpolatePath(path: string, values: Record<string, unknown>): string {\n return path\n .replace(/\\/:([A-Za-z0-9_]+)\\?/g, (_, k: string) =>\n values[k] === undefined ? '' : `/${encodeSegment(k, values[k])}`,\n )\n .replace(PARAM_RE, (_, a?: string, b?: string) => {\n const k = (a ?? b) as string;\n return encodeSegment(k, values[k]);\n });\n}\n\n/** Join path segments, normalising slashes. */\nexport function joinPaths(...parts: (string | undefined)[]): string {\n const joined = parts\n .filter((p): p is string => !!p && p !== '/')\n .map((p) => p.replace(/^\\/+|\\/+$/g, ''))\n .filter(Boolean)\n .join('/');\n return `/${joined}`;\n}\n\n/** `GET /users/:id/orders` -> `get_users_by_id_orders` */\nexport function toolNameFromRoute(method: string, path: string): string {\n const segments = path\n .split('/')\n .filter(Boolean)\n .map((s) => {\n const m = /^(?::([A-Za-z0-9_]+)\\??|\\{([A-Za-z0-9_]+)\\})$/.exec(s);\n return m ? `by_${m[1] ?? m[2]}` : s;\n });\n return sanitizeToolName([method.toLowerCase(), ...segments].join('_'));\n}\n\nexport function sanitizeToolName(name: string): string {\n return name\n .replace(/[^A-Za-z0-9_-]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n .slice(0, 64);\n}\n\nfunction defaultAnnotations(method: string): ToolAnnotations {\n switch (method) {\n case 'GET':\n case 'HEAD':\n return { readOnlyHint: true, openWorldHint: false };\n case 'DELETE':\n return { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false };\n case 'PUT':\n return { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };\n default:\n return { readOnlyHint: false, destructiveHint: false, openWorldHint: false };\n }\n}\n\ninterface ArgMapping {\n params: string[];\n query: Set<string>;\n body: Set<string>;\n /** Body schema is not an object: the whole body is passed under the `body` key. */\n wholeBody: boolean;\n bodyMethod: boolean;\n}\n\n/**\n * Build the flat input schema an agent sees, and remember which argument goes\n * to the path, query string or body when the tool is called.\n */\nexport function buildInputSchema(\n route: RouteSpec,\n opts: RouteToolOptions,\n): { schema: JsonSchema; mapping: ArgMapping } {\n const method = route.method.toUpperCase();\n const params = pathParams(route.path);\n const mapping: ArgMapping = {\n params,\n query: new Set(),\n body: new Set(),\n wholeBody: false,\n bodyMethod: BODY_METHODS.has(method),\n };\n\n if (opts.input) {\n const schema = toJsonSchema(opts.input) as JsonSchema;\n return { schema: { type: 'object', ...schema }, mapping };\n }\n\n const properties: Record<string, JsonSchema> = {};\n const required = new Set<string>();\n\n const paramSchema = toJsonSchema(opts.params);\n for (const p of params) {\n properties[p] = paramSchema?.properties?.[p] ?? { type: 'string', description: `Path parameter \"${p}\"` };\n if (!route.path.includes(`:${p}?`)) required.add(p);\n }\n\n const querySchema = toJsonSchema(opts.query);\n for (const [k, v] of Object.entries(querySchema?.properties ?? {})) {\n properties[k] = v;\n mapping.query.add(k);\n }\n for (const k of querySchema?.required ?? []) required.add(k);\n\n const bodySchema = toJsonSchema(opts.body);\n if (bodySchema) {\n if (bodySchema.properties && (bodySchema.type === undefined || bodySchema.type === 'object')) {\n for (const [k, v] of Object.entries(bodySchema.properties)) {\n properties[k] = v;\n mapping.body.add(k);\n }\n for (const k of bodySchema.required ?? []) required.add(k);\n } else {\n properties.body = bodySchema;\n required.add('body');\n mapping.wholeBody = true;\n }\n }\n\n const schema: JsonSchema = { type: 'object', properties };\n if (required.size) schema.required = [...required];\n return { schema, mapping };\n}\n\nfunction splitArgs(args: Record<string, unknown>, mapping: ArgMapping) {\n const pathValues: Record<string, unknown> = {};\n const query: Record<string, string | string[]> = {};\n let body: Record<string, unknown> | unknown | undefined;\n\n for (const [k, v] of Object.entries(args)) {\n if (v === undefined) continue;\n if (mapping.params.includes(k)) {\n pathValues[k] = v;\n } else if (mapping.wholeBody && k === 'body') {\n body = v;\n } else if (mapping.query.has(k) || (!mapping.body.has(k) && !mapping.bodyMethod)) {\n query[k] = Array.isArray(v) ? v.map(String) : typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v);\n } else {\n body = { ...((body as Record<string, unknown>) ?? {}), [k]: v };\n }\n }\n if (body === undefined && mapping.bodyMethod) body = {};\n return { pathValues, query, body };\n}\n\nexport function responseToResult(res: RouteResponse, maxChars: number): ToolResult {\n const text = truncate(res.body, maxChars);\n const isError = res.status >= 400;\n const result: ToolResult = {\n content: [{ type: 'text', text: isError ? `HTTP ${res.status}\\n${text}` : text || `HTTP ${res.status}` }],\n };\n if (isError) {\n result.isError = true;\n return result;\n }\n if ((res.headers['content-type'] ?? '').includes('json') && text === res.body) {\n try {\n const parsed = JSON.parse(res.body);\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) result.structuredContent = parsed;\n } catch {\n /* not JSON after all */\n }\n }\n return result;\n}\n\nfunction safeDecode(segment: string): string {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n}\n\nfunction truncate(text: string, maxChars: number): string {\n return text.length > maxChars ? `${text.slice(0, maxChars)}\\n…[truncated ${text.length - maxChars} chars]` : text;\n}\n\n/** Add the parsed JSON body (when the response is JSON) and an `ok` flag. */\nexport function toRouteToolResponse(res: RouteResponse): RouteToolResponse {\n let json: unknown;\n if ((res.headers['content-type'] ?? '').includes('json') && res.body) {\n try {\n json = JSON.parse(res.body);\n } catch {\n /* not JSON after all */\n }\n }\n return { ...res, json, ok: res.status < 400 };\n}\n\n/**\n * Turn what a `transformResponse` hook returned into the tool result. Plain values\n * keep the route's error status; ToolResults are used as they are. Text is capped\n * at `maxChars` either way.\n */\nfunction transformedResult(value: unknown, res: RouteToolResponse, maxChars: number): ToolResult {\n const explicit = isToolResult(value);\n const result = toToolResult(value);\n if (!explicit && !res.ok) {\n result.isError = true;\n delete result.structuredContent;\n }\n let truncated = false;\n const content = result.content.map((c) => {\n if (c.type !== 'text' || c.text.length <= maxChars) return c;\n truncated = true;\n return { ...c, text: truncate(c.text, maxChars) };\n });\n if (!truncated) return result;\n // The text no longer matches the structured data, so only keep the text.\n const { structuredContent: _dropped, ...rest } = result;\n return { ...rest, content };\n}\n\nexport function pickForwardHeaders(ctx: ToolContext, names: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of names) {\n const v = ctx.headers[name.toLowerCase()];\n if (v !== undefined) out[name.toLowerCase()] = v;\n }\n return out;\n}\n\n/**\n * Turn an HTTP route + options into an MCP tool whose handler calls the route\n * through `dispatch`, so auth guards, validation and rate limits all still apply.\n */\nexport function createRouteTool(\n route: RouteSpec,\n opts: RouteToolOptions,\n dispatch: Dispatcher,\n serverOpts: Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars' | 'transformResponse'> = {},\n): McpToolDefinition {\n const method = route.method.toUpperCase();\n const name = sanitizeToolName(opts.name ?? toolNameFromRoute(method, route.path));\n const { schema, mapping } = buildInputSchema(route, opts);\n const forward = serverOpts.forwardHeaders ?? DEFAULT_FORWARD_HEADERS;\n const maxChars = serverOpts.maxResponseChars ?? 100_000;\n const transform = opts.transformResponse ?? serverOpts.transformResponse;\n\n return {\n name,\n title: opts.title,\n description: opts.description ?? `${method} ${route.path}`,\n inputSchema: schema,\n annotations: { ...defaultAnnotations(method), ...opts.annotations },\n scopes: opts.scopes,\n validate: toValidator(opts.input),\n async handler(args, ctx) {\n const missing = opts.input ? undefined : checkRequired(schema, args);\n if (missing) return { isError: true, content: [{ type: 'text', text: missing }] };\n\n const { pathValues, query, body } = splitArgs(args, mapping);\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...pickForwardHeaders(ctx, forward),\n ...opts.headers,\n 'x-mcp-tool': name,\n };\n if (ctx.clientIp) headers['x-forwarded-for'] = ctx.clientIp;\n if (body !== undefined) headers['content-type'] = 'application/json';\n\n let path: string;\n try {\n path = interpolatePath(route.path, pathValues);\n } catch (err) {\n return { isError: true, content: [{ type: 'text', text: (err as Error).message }] };\n }\n const request: RouteRequest = { method, path, query, body, headers };\n const res = await dispatch(request, ctx);\n if (!transform) return responseToResult(res, maxChars);\n\n const { 'content-type': _ct, ...baseHeaders } = headers;\n const hookCtx: ResponseTransformContext = {\n tool: name,\n args,\n request,\n toolContext: ctx,\n defaultResult: () => responseToResult(res, maxChars),\n async callRoute(r) {\n if (!r.path.startsWith('/')) {\n throw new Error(`callRoute: path must start with \"/\", got ${JSON.stringify(r.path)}`);\n }\n // Placeholders are encoded like tool arguments; dot segments are never allowed.\n const params = r.params ?? {};\n const missing = pathParams(r.path).filter((p) => params[p] === undefined && !r.path.includes(`:${p}?`));\n if (missing.length) throw new Error(`callRoute: missing params for ${r.path}: ${missing.join(', ')}`);\n const subPath = interpolatePath(r.path, params);\n if (subPath.split('/').some((seg) => ['.', '..'].includes(safeDecode(seg)))) {\n throw new Error(`callRoute: path must not contain \".\" or \"..\" segments: ${JSON.stringify(subPath)}`);\n }\n const sub: RouteRequest = {\n method: (r.method ?? 'GET').toUpperCase(),\n path: subPath,\n query: r.query ?? {},\n body: r.body,\n headers: { ...baseHeaders, ...r.headers },\n };\n if (sub.body !== undefined) sub.headers['content-type'] = 'application/json';\n return toRouteToolResponse(await dispatch(sub, ctx));\n },\n };\n const response = toRouteToolResponse(res);\n const value = await transform(response, hookCtx);\n return value === undefined ? responseToResult(res, maxChars) : transformedResult(value, response, maxChars);\n },\n };\n}\n","import type { Dispatcher, RouteRequest, ToolContext } from './types.js';\n\nexport function buildUrl(base: string, req: Pick<RouteRequest, 'path' | 'query'>): string {\n const url = new URL(base.replace(/\\/+$/, '') + req.path);\n for (const [k, v] of Object.entries(req.query)) {\n for (const item of Array.isArray(v) ? v : [v]) url.searchParams.append(k, item);\n }\n return url.toString();\n}\n\nexport interface FetchDispatcherOptions {\n /**\n * Base URL of the API, e.g. `http://127.0.0.1:3000` or `https://api.example.com/v1`.\n * A function lets adapters resolve it per call (e.g. from the local port).\n */\n baseUrl: string | ((ctx: ToolContext) => string);\n /** Custom fetch implementation. Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout in ms. @default 30_000 */\n timeoutMs?: number;\n}\n\n/**\n * Dispatches tool calls as real HTTP requests. Used for loopback calls into the\n * host app (Express, Koa, NestJS) and for standalone gateways in front of any API.\n */\nexport function createFetchDispatcher(opts: FetchDispatcherOptions): Dispatcher {\n const doFetch = opts.fetch ?? fetch;\n return async (req, ctx) => {\n const base = typeof opts.baseUrl === 'function' ? opts.baseUrl(ctx) : opts.baseUrl;\n const res = await doFetch(buildUrl(base, req), {\n method: req.method,\n headers: req.headers,\n body:\n req.body === undefined || req.method === 'GET' || req.method === 'HEAD' ? undefined : JSON.stringify(req.body),\n signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),\n });\n const headers: Record<string, string> = {};\n res.headers.forEach((v, k) => (headers[k] = v));\n return { status: res.status, headers, body: await res.text() };\n };\n}\n","import { createRouteTool } from './route-tool.js';\nimport { toToolResult } from './result.js';\nimport { toJsonSchema, toValidator } from './schema.js';\n\nexport { toToolResult } from './result.js';\nimport type {\n Dispatcher,\n JsonSchema,\n McpServerOptions,\n McpToolDefinition,\n RouteToolOptions,\n SchemaLike,\n ToolAnnotations,\n ToolContext,\n} from './types.js';\n\nexport interface DefineToolOptions {\n name: string;\n title?: string;\n description: string;\n input?: SchemaLike;\n annotations?: ToolAnnotations;\n /** OAuth scopes needed to call this tool (when the `oauth` option is enabled). */\n scopes?: string[];\n /** Return a string, any JSON value, or a full ToolResult. */\n handler: (args: any, ctx: ToolContext) => unknown;\n}\n\n/** Define a code-only tool that is not backed by an HTTP route. */\nexport function defineTool(opts: DefineToolOptions): McpToolDefinition {\n return {\n name: opts.name,\n title: opts.title,\n description: opts.description,\n inputSchema: { type: 'object', ...(toJsonSchema(opts.input) ?? { properties: {} }) },\n annotations: opts.annotations,\n scopes: opts.scopes,\n validate: toValidator(opts.input),\n async handler(args, ctx) {\n return toToolResult(await opts.handler(args, ctx));\n },\n };\n}\n\ninterface OpenApiOperation {\n operationId?: string;\n summary?: string;\n description?: string;\n parameters?: { name: string; in: string; required?: boolean; description?: string; schema?: JsonSchema }[];\n requestBody?: { content?: Record<string, { schema?: JsonSchema }> };\n 'x-mcp'?: boolean | RouteToolOptions;\n}\n\nexport interface FromOpenApiOptions {\n /**\n * Which operations to expose. Defaults to operations marked with `x-mcp: true`\n * (or an `x-mcp` options object). Pass `() => true` to expose everything.\n */\n include?: (op: { method: string; path: string; operation: OpenApiOperation }) => boolean;\n}\n\n/**\n * Build tools from an OpenAPI 3.x document. Works with any framework that can\n * emit OpenAPI (e.g. @nestjs/swagger, @fastify/swagger, tsoa, hono-openapi).\n * `$ref`s are not resolved, so pass a dereferenced document.\n */\nexport function toolsFromOpenApi(\n doc: { paths?: Record<string, Record<string, OpenApiOperation>> },\n dispatch: Dispatcher,\n opts: FromOpenApiOptions & Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars' | 'transformResponse'> = {},\n): McpToolDefinition[] {\n const include = opts.include ?? (({ operation }) => !!operation['x-mcp']);\n const methods = ['get', 'post', 'put', 'patch', 'delete'];\n const tools: McpToolDefinition[] = [];\n\n for (const [path, item] of Object.entries(doc.paths ?? {})) {\n for (const method of methods) {\n const operation = item[method];\n if (!operation || !include({ method, path, operation })) continue;\n const extra = typeof operation['x-mcp'] === 'object' ? operation['x-mcp'] : {};\n\n const query: JsonSchema = { type: 'object', properties: {}, required: [] };\n const params: JsonSchema = { type: 'object', properties: {} };\n for (const p of operation.parameters ?? []) {\n const s = { ...(p.schema ?? { type: 'string' }), ...(p.description ? { description: p.description } : {}) };\n if (p.in === 'query') {\n query.properties![p.name] = s;\n if (p.required) query.required!.push(p.name);\n } else if (p.in === 'path') params.properties![p.name] = s;\n }\n const body = operation.requestBody?.content?.['application/json']?.schema;\n\n tools.push(\n createRouteTool(\n { method, path },\n {\n name: operation.operationId,\n description: operation.description ?? operation.summary,\n params,\n query,\n body,\n ...extra,\n },\n dispatch,\n opts,\n ),\n );\n }\n }\n return tools;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;ACiEO,IAAMA,gCAAgC;AAOtC,SAASC,+BAA+BC,UAAgB;AAC7D,QAAMC,WAAW,IAAIC,IAAIF,QAAAA,EAAUC,SAASE,QAAQ,QAAQ,EAAA;AAC5D,SAAOF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AU,OAAA,IAAW,CAAC;AAE7E,YAAMU,QAAoB;QAAE1B,MAAM;QAAUG,YAAY,CAAC;QAAGwB,UAAU,CAAA;MAAG;AACzE,YAAMC,SAAqB;QAAE5B,MAAM;QAAUG,YAAY,CAAC;MAAE;AAC5D,iBAAW0B,KAAKb,UAAUc,cAAc,CAAA,GAAI;AAC1C,cAAMC,IAAI;UAAE,GAAIF,EAAEG,UAAU;YAAEhC,MAAM;UAAS;UAAI,GAAI6B,EAAE/B,cAAc;YAAEA,aAAa+B,EAAE/B;UAAY,IAAI,CAAC;QAAG;AAC1G,YAAI+B,EAAEI,OAAO,SAAS;AACpBP,gBAAMvB,WAAY0B,EAAEjC,IAAI,IAAImC;AAC5B,cAAIF,EAAEF,SAAUD,OAAMC,SAAUO,KAAKL,EAAEjC,IAAI;QAC7C,WAAWiC,EAAEI,OAAO,OAAQL,QAAOzB,WAAY0B,EAAEjC,IAAI,IAAImC;MAC3D;AACA,YAAMI,OAAOnB,UAAUoB,aAAaC,UAAU,kBAAA,GAAqBL;AAEnEd,YAAMgB,KACJI,gBACE;QAAEd;QAAQL;MAAK,GACf;QACEvB,MAAMoB,UAAUuB;QAChBzC,aAAakB,UAAUlB,eAAekB,UAAUwB;QAChDZ;QACAF;QACAS;QACA,GAAGV;MACL,GACAX,UACAnB,IAAAA,CAAAA;IAGN;EACF;AACA,SAAOuB;AACT;AA5CgBN;","names":["PROTECTED_RESOURCE_WELL_KNOWN","protectedResourceMetadataPaths","resource","pathname","URL","replace","protectedResourceMetadataUrl","href","validateOAuthOptions","o","url","Error","JSON","stringify","hash","authorizationServers","length","verifyToken","quote","v","bearerChallenge","params","parts","error","push","errorDescription","scope","join","bearerToken","headers","m","exec","authorization","authenticate","token","ok","status","description","challenge","requiredScopes","auth","undefined","deny","expiresAt","Date","now","missing","missingScopes","Set","scopes","required","granted","filter","s","has","parseScopes","value","Array","isArray","map","String","split","Boolean","SUPPORTED_PROTOCOL_VERSIONS","LATEST_PROTOCOL_VERSION","PARSE_ERROR","INVALID_REQUEST","METHOD_NOT_FOUND","INVALID_PARAMS","ok","id","result","jsonrpc","fail","code","message","error","McpServer","tools","Map","loaders","options","oauth","validateOAuthOptions","addTool","tool","has","name","Error","set","onLoad","loader","push","listTools","load","values","length","l","handleMessage","ctx","Array","isArray","results","Promise","all","map","m","handleOne","filter","r","msg","method","undefined","params","requested","protocolVersion","includes","capabilities","listChanged","serverInfo","version","instructions","t","title","description","inputSchema","annotations","get","String","callTool","arguments","resources","prompts","args","validate","v","isError","content","type","text","value","handler","err","isOriginAllowed","origin","allowed","allowedOrigins","oauthMetadataPaths","protectedResourceMetadataPaths","resource","protectedResourceMetadata","o","scopes","scopesSupported","Set","requiredScopes","flatMap","authorization_servers","authorizationServers","scopes_supported","bearer_methods_supported","resourceName","resource_name","resourceDocumentation","resource_documentation","metadata","handleMetadataHttp","req","cors","toUpperCase","status","headers","allow","body","JSON","stringify","handleHttp","json","outcome","authenticate","authError","auth","Uint8Array","parse","TextDecoder","decode","calls","missing","missingScopes","scope","deny","join","response","challenge","error_description","isToolResult","value","content","Array","isArray","length","every","c","type","toToolResult","text","JSON","stringify","result","structuredContent","isStandard","s","toJsonSchema","schema","undefined","out","jsonSchema","input","target","toJSONSchema","Error","$schema","_ignored","rest","toValidator","validate","value","result","issues","ok","message","map","i","path","p","String","key","join","checkRequired","args","missing","required","filter","k","length","DEFAULT_FORWARD_HEADERS","BODY_METHODS","Set","PARAM_RE","pathParams","path","matchAll","map","m","encodeSegment","name","value","raw","String","Error","JSON","stringify","encodeURIComponent","interpolatePath","values","replace","_","k","undefined","a","b","toolNameFromRoute","method","path","segments","split","filter","Boolean","map","s","m","exec","sanitizeToolName","toLowerCase","join","name","replace","slice","defaultAnnotations","readOnlyHint","openWorldHint","destructiveHint","idempotentHint","buildInputSchema","route","opts","toUpperCase","params","pathParams","mapping","query","Set","body","wholeBody","bodyMethod","BODY_METHODS","has","input","schema","toJsonSchema","type","properties","required","paramSchema","p","description","includes","add","querySchema","k","v","Object","entries","bodySchema","undefined","size","splitArgs","args","pathValues","Array","isArray","String","JSON","stringify","responseToResult","res","maxChars","text","truncate","isError","status","result","content","headers","parsed","parse","structuredContent","safeDecode","segment","decodeURIComponent","length","toRouteToolResponse","json","ok","transformedResult","value","explicit","isToolResult","toToolResult","truncated","c","_dropped","rest","pickForwardHeaders","ctx","names","out","createRouteTool","dispatch","serverOpts","forward","forwardHeaders","DEFAULT_FORWARD_HEADERS","maxResponseChars","transform","transformResponse","title","inputSchema","annotations","scopes","validate","toValidator","handler","missing","checkRequired","accept","clientIp","interpolatePath","err","message","request","_ct","baseHeaders","hookCtx","tool","toolContext","defaultResult","callRoute","r","startsWith","Error","subPath","some","seg","sub","response","buildUrl","base","req","url","URL","replace","path","k","v","Object","entries","query","item","Array","isArray","searchParams","append","toString","createFetchDispatcher","opts","doFetch","fetch","ctx","baseUrl","res","method","headers","body","undefined","JSON","stringify","signal","AbortSignal","timeout","timeoutMs","forEach","status","text","defineTool","opts","name","title","description","inputSchema","type","toJsonSchema","input","properties","annotations","scopes","validate","toValidator","handler","args","ctx","toToolResult","toolsFromOpenApi","doc","dispatch","include","operation","methods","tools","path","item","Object","entries","paths","method","extra","query","required","params","p","parameters","s","schema","in","push","body","requestBody","content","createRouteTool","operationId","summary"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { c as RouteSpec, R as RouteToolOptions, D as Dispatcher, M as McpServerOptions, a as McpToolDefinition, T as ToolContext, S as SchemaLike,
|
|
2
|
-
export { f as JsonRpcResponse, L as LATEST_PROTOCOL_VERSION, g as McpHttpRequest, h as McpHttpResponse, b as McpServer, i as
|
|
1
|
+
import { c as RouteSpec, R as RouteToolOptions, D as Dispatcher, M as McpServerOptions, a as McpToolDefinition, T as ToolContext, d as ToolResult, S as SchemaLike, e as ToolAnnotations, J as JsonSchema } from './server--mQVQq3A.cjs';
|
|
2
|
+
export { f as JsonRpcResponse, L as LATEST_PROTOCOL_VERSION, g as McpHttpRequest, h as McpHttpResponse, b as McpServer, i as ResponseTransform, j as ResponseTransformContext, k as RouteRequest, l as RouteResponse, m as RouteToolResponse, n as SUPPORTED_PROTOCOL_VERSIONS, o as TextContent } from './server--mQVQq3A.cjs';
|
|
3
3
|
export { A as AuthInfo, O as OAuthOptions, T as TokenVerifier, V as VerifyTokenContext, b as bearerChallenge, p as parseScopes, a as protectedResourceMetadataPaths, c as protectedResourceMetadataUrl } from './oauth-8RmQamGP.cjs';
|
|
4
4
|
|
|
5
5
|
declare const DEFAULT_FORWARD_HEADERS: string[];
|
|
@@ -7,7 +7,7 @@ declare const DEFAULT_FORWARD_HEADERS: string[];
|
|
|
7
7
|
* Turn an HTTP route + options into an MCP tool whose handler calls the route
|
|
8
8
|
* through `dispatch`, so auth guards, validation and rate limits all still apply.
|
|
9
9
|
*/
|
|
10
|
-
declare function createRouteTool(route: RouteSpec, opts: RouteToolOptions, dispatch: Dispatcher, serverOpts?: Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars'>): McpToolDefinition;
|
|
10
|
+
declare function createRouteTool(route: RouteSpec, opts: RouteToolOptions, dispatch: Dispatcher, serverOpts?: Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars' | 'transformResponse'>): McpToolDefinition;
|
|
11
11
|
|
|
12
12
|
interface FetchDispatcherOptions {
|
|
13
13
|
/**
|
|
@@ -26,6 +26,9 @@ interface FetchDispatcherOptions {
|
|
|
26
26
|
*/
|
|
27
27
|
declare function createFetchDispatcher(opts: FetchDispatcherOptions): Dispatcher;
|
|
28
28
|
|
|
29
|
+
/** Turn a handler's return value (string, JSON value or ToolResult) into a ToolResult. */
|
|
30
|
+
declare function toToolResult(value: unknown): ToolResult;
|
|
31
|
+
|
|
29
32
|
interface DefineToolOptions {
|
|
30
33
|
name: string;
|
|
31
34
|
title?: string;
|
|
@@ -39,7 +42,6 @@ interface DefineToolOptions {
|
|
|
39
42
|
}
|
|
40
43
|
/** Define a code-only tool that is not backed by an HTTP route. */
|
|
41
44
|
declare function defineTool(opts: DefineToolOptions): McpToolDefinition;
|
|
42
|
-
declare function toToolResult(value: unknown): ToolResult;
|
|
43
45
|
interface OpenApiOperation {
|
|
44
46
|
operationId?: string;
|
|
45
47
|
summary?: string;
|
|
@@ -76,7 +78,7 @@ interface FromOpenApiOptions {
|
|
|
76
78
|
*/
|
|
77
79
|
declare function toolsFromOpenApi(doc: {
|
|
78
80
|
paths?: Record<string, Record<string, OpenApiOperation>>;
|
|
79
|
-
}, dispatch: Dispatcher, opts?: FromOpenApiOptions & Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars'>): McpToolDefinition[];
|
|
81
|
+
}, dispatch: Dispatcher, opts?: FromOpenApiOptions & Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars' | 'transformResponse'>): McpToolDefinition[];
|
|
80
82
|
|
|
81
83
|
/** Convert any supported schema flavour into a plain JSON Schema object. */
|
|
82
84
|
declare function toJsonSchema(schema: SchemaLike | undefined): JsonSchema | undefined;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { c as RouteSpec, R as RouteToolOptions, D as Dispatcher, M as McpServerOptions, a as McpToolDefinition, T as ToolContext, S as SchemaLike,
|
|
2
|
-
export { f as JsonRpcResponse, L as LATEST_PROTOCOL_VERSION, g as McpHttpRequest, h as McpHttpResponse, b as McpServer, i as
|
|
1
|
+
import { c as RouteSpec, R as RouteToolOptions, D as Dispatcher, M as McpServerOptions, a as McpToolDefinition, T as ToolContext, d as ToolResult, S as SchemaLike, e as ToolAnnotations, J as JsonSchema } from './server-BPDTsT2o.js';
|
|
2
|
+
export { f as JsonRpcResponse, L as LATEST_PROTOCOL_VERSION, g as McpHttpRequest, h as McpHttpResponse, b as McpServer, i as ResponseTransform, j as ResponseTransformContext, k as RouteRequest, l as RouteResponse, m as RouteToolResponse, n as SUPPORTED_PROTOCOL_VERSIONS, o as TextContent } from './server-BPDTsT2o.js';
|
|
3
3
|
export { A as AuthInfo, O as OAuthOptions, T as TokenVerifier, V as VerifyTokenContext, b as bearerChallenge, p as parseScopes, a as protectedResourceMetadataPaths, c as protectedResourceMetadataUrl } from './oauth-8RmQamGP.js';
|
|
4
4
|
|
|
5
5
|
declare const DEFAULT_FORWARD_HEADERS: string[];
|
|
@@ -7,7 +7,7 @@ declare const DEFAULT_FORWARD_HEADERS: string[];
|
|
|
7
7
|
* Turn an HTTP route + options into an MCP tool whose handler calls the route
|
|
8
8
|
* through `dispatch`, so auth guards, validation and rate limits all still apply.
|
|
9
9
|
*/
|
|
10
|
-
declare function createRouteTool(route: RouteSpec, opts: RouteToolOptions, dispatch: Dispatcher, serverOpts?: Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars'>): McpToolDefinition;
|
|
10
|
+
declare function createRouteTool(route: RouteSpec, opts: RouteToolOptions, dispatch: Dispatcher, serverOpts?: Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars' | 'transformResponse'>): McpToolDefinition;
|
|
11
11
|
|
|
12
12
|
interface FetchDispatcherOptions {
|
|
13
13
|
/**
|
|
@@ -26,6 +26,9 @@ interface FetchDispatcherOptions {
|
|
|
26
26
|
*/
|
|
27
27
|
declare function createFetchDispatcher(opts: FetchDispatcherOptions): Dispatcher;
|
|
28
28
|
|
|
29
|
+
/** Turn a handler's return value (string, JSON value or ToolResult) into a ToolResult. */
|
|
30
|
+
declare function toToolResult(value: unknown): ToolResult;
|
|
31
|
+
|
|
29
32
|
interface DefineToolOptions {
|
|
30
33
|
name: string;
|
|
31
34
|
title?: string;
|
|
@@ -39,7 +42,6 @@ interface DefineToolOptions {
|
|
|
39
42
|
}
|
|
40
43
|
/** Define a code-only tool that is not backed by an HTTP route. */
|
|
41
44
|
declare function defineTool(opts: DefineToolOptions): McpToolDefinition;
|
|
42
|
-
declare function toToolResult(value: unknown): ToolResult;
|
|
43
45
|
interface OpenApiOperation {
|
|
44
46
|
operationId?: string;
|
|
45
47
|
summary?: string;
|
|
@@ -76,7 +78,7 @@ interface FromOpenApiOptions {
|
|
|
76
78
|
*/
|
|
77
79
|
declare function toolsFromOpenApi(doc: {
|
|
78
80
|
paths?: Record<string, Record<string, OpenApiOperation>>;
|
|
79
|
-
}, dispatch: Dispatcher, opts?: FromOpenApiOptions & Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars'>): McpToolDefinition[];
|
|
81
|
+
}, dispatch: Dispatcher, opts?: FromOpenApiOptions & Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars' | 'transformResponse'>): McpToolDefinition[];
|
|
80
82
|
|
|
81
83
|
/** Convert any supported schema flavour into a plain JSON Schema object. */
|
|
82
84
|
declare function toJsonSchema(schema: SchemaLike | undefined): JsonSchema | undefined;
|
package/dist/index.js
CHANGED
|
@@ -449,6 +449,38 @@ function authError(o) {
|
|
|
449
449
|
}
|
|
450
450
|
__name(authError, "authError");
|
|
451
451
|
|
|
452
|
+
// src/core/result.ts
|
|
453
|
+
function isToolResult(value) {
|
|
454
|
+
const content = value?.content;
|
|
455
|
+
return !!value && typeof value === "object" && Array.isArray(content) && content.length > 0 && content.every((c) => !!c && typeof c === "object" && typeof c.type === "string");
|
|
456
|
+
}
|
|
457
|
+
__name(isToolResult, "isToolResult");
|
|
458
|
+
function toToolResult(value) {
|
|
459
|
+
if (isToolResult(value)) return value;
|
|
460
|
+
if (typeof value === "string") return {
|
|
461
|
+
content: [
|
|
462
|
+
{
|
|
463
|
+
type: "text",
|
|
464
|
+
text: value
|
|
465
|
+
}
|
|
466
|
+
]
|
|
467
|
+
};
|
|
468
|
+
const text = JSON.stringify(value ?? null);
|
|
469
|
+
const result = {
|
|
470
|
+
content: [
|
|
471
|
+
{
|
|
472
|
+
type: "text",
|
|
473
|
+
text
|
|
474
|
+
}
|
|
475
|
+
]
|
|
476
|
+
};
|
|
477
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
478
|
+
result.structuredContent = value;
|
|
479
|
+
}
|
|
480
|
+
return result;
|
|
481
|
+
}
|
|
482
|
+
__name(toToolResult, "toToolResult");
|
|
483
|
+
|
|
452
484
|
// src/core/schema.ts
|
|
453
485
|
function isStandard(s) {
|
|
454
486
|
return typeof s === "object" && s !== null && "~standard" in s;
|
|
@@ -669,9 +701,7 @@ function splitArgs(args, mapping) {
|
|
|
669
701
|
}
|
|
670
702
|
__name(splitArgs, "splitArgs");
|
|
671
703
|
function responseToResult(res, maxChars) {
|
|
672
|
-
|
|
673
|
-
if (text.length > maxChars) text = `${text.slice(0, maxChars)}
|
|
674
|
-
\u2026[truncated ${text.length - maxChars} chars]`;
|
|
704
|
+
const text = truncate(res.body, maxChars);
|
|
675
705
|
const isError = res.status >= 400;
|
|
676
706
|
const result = {
|
|
677
707
|
content: [
|
|
@@ -696,6 +726,58 @@ ${text}` : text || `HTTP ${res.status}`
|
|
|
696
726
|
return result;
|
|
697
727
|
}
|
|
698
728
|
__name(responseToResult, "responseToResult");
|
|
729
|
+
function safeDecode(segment) {
|
|
730
|
+
try {
|
|
731
|
+
return decodeURIComponent(segment);
|
|
732
|
+
} catch {
|
|
733
|
+
return segment;
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
__name(safeDecode, "safeDecode");
|
|
737
|
+
function truncate(text, maxChars) {
|
|
738
|
+
return text.length > maxChars ? `${text.slice(0, maxChars)}
|
|
739
|
+
\u2026[truncated ${text.length - maxChars} chars]` : text;
|
|
740
|
+
}
|
|
741
|
+
__name(truncate, "truncate");
|
|
742
|
+
function toRouteToolResponse(res) {
|
|
743
|
+
let json;
|
|
744
|
+
if ((res.headers["content-type"] ?? "").includes("json") && res.body) {
|
|
745
|
+
try {
|
|
746
|
+
json = JSON.parse(res.body);
|
|
747
|
+
} catch {
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
return {
|
|
751
|
+
...res,
|
|
752
|
+
json,
|
|
753
|
+
ok: res.status < 400
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
__name(toRouteToolResponse, "toRouteToolResponse");
|
|
757
|
+
function transformedResult(value, res, maxChars) {
|
|
758
|
+
const explicit = isToolResult(value);
|
|
759
|
+
const result = toToolResult(value);
|
|
760
|
+
if (!explicit && !res.ok) {
|
|
761
|
+
result.isError = true;
|
|
762
|
+
delete result.structuredContent;
|
|
763
|
+
}
|
|
764
|
+
let truncated = false;
|
|
765
|
+
const content = result.content.map((c) => {
|
|
766
|
+
if (c.type !== "text" || c.text.length <= maxChars) return c;
|
|
767
|
+
truncated = true;
|
|
768
|
+
return {
|
|
769
|
+
...c,
|
|
770
|
+
text: truncate(c.text, maxChars)
|
|
771
|
+
};
|
|
772
|
+
});
|
|
773
|
+
if (!truncated) return result;
|
|
774
|
+
const { structuredContent: _dropped, ...rest } = result;
|
|
775
|
+
return {
|
|
776
|
+
...rest,
|
|
777
|
+
content
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
__name(transformedResult, "transformedResult");
|
|
699
781
|
function pickForwardHeaders(ctx, names) {
|
|
700
782
|
const out = {};
|
|
701
783
|
for (const name of names) {
|
|
@@ -711,6 +793,7 @@ function createRouteTool(route, opts, dispatch, serverOpts = {}) {
|
|
|
711
793
|
const { schema, mapping } = buildInputSchema(route, opts);
|
|
712
794
|
const forward = serverOpts.forwardHeaders ?? DEFAULT_FORWARD_HEADERS;
|
|
713
795
|
const maxChars = serverOpts.maxResponseChars ?? 1e5;
|
|
796
|
+
const transform = opts.transformResponse ?? serverOpts.transformResponse;
|
|
714
797
|
return {
|
|
715
798
|
name,
|
|
716
799
|
title: opts.title,
|
|
@@ -756,14 +839,53 @@ function createRouteTool(route, opts, dispatch, serverOpts = {}) {
|
|
|
756
839
|
]
|
|
757
840
|
};
|
|
758
841
|
}
|
|
759
|
-
const
|
|
842
|
+
const request = {
|
|
760
843
|
method,
|
|
761
844
|
path,
|
|
762
845
|
query,
|
|
763
846
|
body,
|
|
764
847
|
headers
|
|
765
|
-
}
|
|
766
|
-
|
|
848
|
+
};
|
|
849
|
+
const res = await dispatch(request, ctx);
|
|
850
|
+
if (!transform) return responseToResult(res, maxChars);
|
|
851
|
+
const { "content-type": _ct, ...baseHeaders } = headers;
|
|
852
|
+
const hookCtx = {
|
|
853
|
+
tool: name,
|
|
854
|
+
args,
|
|
855
|
+
request,
|
|
856
|
+
toolContext: ctx,
|
|
857
|
+
defaultResult: /* @__PURE__ */ __name(() => responseToResult(res, maxChars), "defaultResult"),
|
|
858
|
+
async callRoute(r) {
|
|
859
|
+
if (!r.path.startsWith("/")) {
|
|
860
|
+
throw new Error(`callRoute: path must start with "/", got ${JSON.stringify(r.path)}`);
|
|
861
|
+
}
|
|
862
|
+
const params = r.params ?? {};
|
|
863
|
+
const missing2 = pathParams(r.path).filter((p) => params[p] === void 0 && !r.path.includes(`:${p}?`));
|
|
864
|
+
if (missing2.length) throw new Error(`callRoute: missing params for ${r.path}: ${missing2.join(", ")}`);
|
|
865
|
+
const subPath = interpolatePath(r.path, params);
|
|
866
|
+
if (subPath.split("/").some((seg) => [
|
|
867
|
+
".",
|
|
868
|
+
".."
|
|
869
|
+
].includes(safeDecode(seg)))) {
|
|
870
|
+
throw new Error(`callRoute: path must not contain "." or ".." segments: ${JSON.stringify(subPath)}`);
|
|
871
|
+
}
|
|
872
|
+
const sub = {
|
|
873
|
+
method: (r.method ?? "GET").toUpperCase(),
|
|
874
|
+
path: subPath,
|
|
875
|
+
query: r.query ?? {},
|
|
876
|
+
body: r.body,
|
|
877
|
+
headers: {
|
|
878
|
+
...baseHeaders,
|
|
879
|
+
...r.headers
|
|
880
|
+
}
|
|
881
|
+
};
|
|
882
|
+
if (sub.body !== void 0) sub.headers["content-type"] = "application/json";
|
|
883
|
+
return toRouteToolResponse(await dispatch(sub, ctx));
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
const response = toRouteToolResponse(res);
|
|
887
|
+
const value = await transform(response, hookCtx);
|
|
888
|
+
return value === void 0 ? responseToResult(res, maxChars) : transformedResult(value, response, maxChars);
|
|
767
889
|
}
|
|
768
890
|
};
|
|
769
891
|
}
|
|
@@ -822,31 +944,6 @@ function defineTool(opts) {
|
|
|
822
944
|
};
|
|
823
945
|
}
|
|
824
946
|
__name(defineTool, "defineTool");
|
|
825
|
-
function toToolResult(value) {
|
|
826
|
-
if (value && typeof value === "object" && Array.isArray(value.content)) return value;
|
|
827
|
-
if (typeof value === "string") return {
|
|
828
|
-
content: [
|
|
829
|
-
{
|
|
830
|
-
type: "text",
|
|
831
|
-
text: value
|
|
832
|
-
}
|
|
833
|
-
]
|
|
834
|
-
};
|
|
835
|
-
const text = JSON.stringify(value ?? null);
|
|
836
|
-
const result = {
|
|
837
|
-
content: [
|
|
838
|
-
{
|
|
839
|
-
type: "text",
|
|
840
|
-
text
|
|
841
|
-
}
|
|
842
|
-
]
|
|
843
|
-
};
|
|
844
|
-
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
845
|
-
result.structuredContent = value;
|
|
846
|
-
}
|
|
847
|
-
return result;
|
|
848
|
-
}
|
|
849
|
-
__name(toToolResult, "toToolResult");
|
|
850
947
|
function toolsFromOpenApi(doc, dispatch, opts = {}) {
|
|
851
948
|
const include = opts.include ?? (({ operation }) => !!operation["x-mcp"]);
|
|
852
949
|
const methods = [
|