@supabase/mcp-utils 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +24 -3
- package/dist/index.d.ts +24 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _server = require('@modelcontextprotocol/server');var _v4 = require('zod/v4');function g(e){try{return new URL(e),e}catch (e2){throw new Error(`invalid uri: ${e}`)}}function T(e,
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _server = require('@modelcontextprotocol/server');var _v4 = require('zod/v4');function g(e){try{return new URL(e),e}catch (e2){throw new Error(`invalid uri: ${e}`)}}function T(e,t){let o=new URL(e),l=new URL(t);return o.href===l.href}function w(e,t){let l=new URL(e).pathname.split("/").slice(1);for(let p of t){let r=new URL(p),s=decodeURIComponent(r.pathname).split("/").slice(1);if(l.length!==s.length)continue;let a={},c=!0;for(let n=0;n<l.length;n++){let m=s[n],R=l[n];if(!m||!R)break;if(m.startsWith("{")&&m.endsWith("}")){let u=m.slice(1,-1);if(!u)break;a[u]=R}else if(l[n]!==s[n]){c=!1;break}}if(c)return{uri:p,params:a}}}function $(e,t){return{uri:e,...t}}function j(e,t){return{uriTemplate:e,...t}}function D(e,t){return{uri:e,mimeType:"application/json",...t}}function I(e,t){return{uriTemplate:e,mimeType:"application/json",...t}}function z(e,t){return t.map(o=>{if("uri"in o){let r=new URL(o.uri,`${e}://`),s=decodeURI(r.href);return{...o,uri:s}}let l=new URL(o.uriTemplate,`${e}://`),p=decodeURI(l.href);return{...o,uriTemplate:p}})}function L(e,t){return{uri:e,mimeType:"application/json",text:JSON.stringify(t)}}function N(e){return e}function q(e){let t={};e.resources&&(t.resources={}),e.tools&&(t.tools={});let o=new (0, _server.Server)({name:e.name,title:e.title,version:e.version},{capabilities:t,instructions:e.instructions,requestState:e.requestState});async function l(){if(!e.resources)throw new Error("resources not available");return typeof e.resources=="function"?await e.resources():e.resources}async function p(r){if(!e.tools)throw new Error("tools not available");return typeof e.tools=="function"?await e.tools(r):e.tools}return o.oninitialized=async()=>{let r=o.getClientVersion(),s=o.getClientCapabilities();if(!r)throw new Error("client info not available after initialization");if(!s)throw new Error("client capabilities not available after initialization");let a={clientInfo:r,clientCapabilities:s};await _optionalChain([e, 'access', _ => _.onInitialize, 'optionalCall', _2 => _2(a)])},e.resources&&(o.setRequestHandler("resources/list",async()=>({resources:(await l()).filter(s=>"uri"in s).map(({uri:s,name:a,description:c,mimeType:n})=>({uri:s,name:a,description:c,mimeType:n}))})),o.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:(await l()).filter(s=>"uriTemplate"in s).map(({uriTemplate:s,name:a,description:c,mimeType:n})=>({uriTemplate:s,name:a,description:c,mimeType:n}))})),o.setRequestHandler("resources/read",async r=>{try{let s=await l(),{uri:a}=r.params,n=s.filter(i=>"uri"in i).find(i=>T(i.uri,a));if(n){let i=await n.read(a);return{contents:Array.isArray(i)?i:[i]}}let m=s.filter(i=>"uriTemplate"in i),R=m.map(({uriTemplate:i})=>g(i)),u=w(a,R);if(!u)throw new Error("resource not found");let y=m.find(i=>i.uriTemplate===u.uri);if(!y)throw new Error("resource not found");let d=await y.read(a,u.params);return{contents:Array.isArray(d)?d:[d]}}catch(s){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:h(s)})}]}}})),e.tools&&(o.setRequestHandler("tools/list",async(r,s)=>{let a=await p(s);return{tools:await Promise.all(Object.entries(a).filter(([,c])=>!c.hidden).map(async([c,{description:n,annotations:m,parameters:R}])=>{let u=_v4.z.toJSONSchema(R,{target:"draft-7"});return{name:c,description:typeof n=="function"?await n():n,annotations:m,inputSchema:u}}))}}),o.setRequestHandler("tools/call",async(r,s)=>{try{let a=await p(s),c=r.params.name;if(!(c in a))throw new Error("tool not found");let n=a[c];if(!n)throw new Error("tool not found");let m=n.parameters.strict().parse(_nullishCoalesce(r.params.arguments, () => ({}))),u=await(async d=>{let f=await d.execute(m,s).then(i=>({success:!0,data:i})).catch(i=>({success:!1,error:i}));try{_optionalChain([e, 'access', _3 => _3.onToolCall, 'optionalCall', _4 => _4({name:c,arguments:m,annotations:d.annotations,...f})])}catch(i){console.error("Failed to run tool callback",i)}if(!f.success)throw f.error;return f.data})(n);return U(u)||_server.isCallToolResult.call(void 0, u)?u:{content:u!=null?[{type:"text",text:JSON.stringify(u)}]:[]}}catch(a){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:h(a)})}]}}})),o}function U(e){return typeof e=="object"&&e!==null&&e.resultType==="input_required"}function h(e){if(!e||typeof e!="object")return e;let t={},o=["name","message"];for(let l of o)l in e&&(t[l]=e[l]);return t}var x=class{#e;#t;constructor(){let t,o,l=new Promise(r=>{t=r}),p=new Promise(r=>{o=r});this.ready=Promise.all([l,p]).then(()=>{}),this.readable=new ReadableStream({start:r=>{this.#e=r,t()}}),this.writable=new WritableStream({start:r=>{this.#t=r,o()},write:r=>{_optionalChain([this, 'access', _5 => _5.onmessage, 'optionalCall', _6 => _6(r)])}})}async start(){await this.ready}async send(t){if(!this.#e)throw new Error("readable stream not initialized");this.#e.enqueue(t)}async close(){_optionalChain([this, 'access', _7 => _7.#e, 'optionalAccess', _8 => _8.error, 'call', _9 => _9(new Error("connection closed"))]),_optionalChain([this, 'access', _10 => _10.#t, 'optionalAccess', _11 => _11.error, 'call', _12 => _12(new Error("connection closed"))]),_optionalChain([this, 'access', _13 => _13.onclose, 'optionalCall', _14 => _14()])}};exports.StreamTransport = x; exports.createMcpServer = q; exports.jsonResource = D; exports.jsonResourceResponse = L; exports.jsonResourceTemplate = I; exports.resource = $; exports.resourceTemplate = j; exports.resources = z; exports.tool = N;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/util.ts"],"names":["assertValidUri","uri"],"mappings":"AAAA,uuBAAuB,4BAWL,SCNFA,CAAAA,CAAeC,CAAAA,CAAa,CAC1C,GAAI,CACF,OAAA,IAAI,GAAA,CAAIA,CAAG,CAAA,CACJA,CACT,CAAA,UAAQ,CACN,MAAM,IAAI,KAAA,CAAM,CAAA,aAAA,EAAgBA,CAAG,CAAA,CAAA","file":"/home/runner/work/mcp/mcp/packages/mcp-utils/dist/index.cjs","sourcesContent":["import { Server } from '@modelcontextprotocol/server';\nimport type {\n ClientCapabilities,\n Implementation,\n ListResourcesResult,\n ListResourceTemplatesResult,\n ListToolsResult,\n Tool as McpTool,\n ReadResourceResult,\n ServerCapabilities,\n} from '@modelcontextprotocol/server';\nimport { z } from 'zod/v4';\n\nimport type { ExtractParams } from './types.js';\nimport { assertValidUri, compareUris, matchUriTemplate } from './util.js';\n\nexport type Scheme = string;\nexport type Annotations = NonNullable<\n ListToolsResult['tools'][number]['annotations']\n>;\n\nexport type Resource<Uri extends string = string, Result = unknown> = {\n uri: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(uri: `${Scheme}://${Uri}`): Promise<Result>;\n};\n\nexport type ResourceTemplate<Uri extends string = string, Result = unknown> = {\n uriTemplate: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(\n uri: `${Scheme}://${Uri}`,\n params: {\n [Param in ExtractParams<Uri>]: string;\n }\n ): Promise<Result>;\n};\n\nexport type Tool<\n Params extends z.ZodObject<any> = z.ZodObject<any>,\n // MCP spec restricts outputSchema to type \"object\" at the root level:\n // https://modelcontextprotocol.io/specification/2025-11-25/schema#tool-outputschema\n OutputSchema extends z.ZodObject<any> = z.ZodObject<any>,\n> = {\n description: Prop<string>;\n annotations?: Annotations;\n parameters: Params;\n outputSchema: OutputSchema;\n /** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */\n hidden?: boolean;\n execute(params: z.infer<Params>): Promise<z.infer<OutputSchema>>;\n};\n\n/**\n * Helper function to define an MCP resource while preserving type information.\n */\nexport function resource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri'>\n): Resource<Uri, Result> {\n return {\n uri,\n ...resource,\n };\n}\n\n/**\n * Helper function to define an MCP resource with a URI template while preserving type information.\n */\nexport function resourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource while preserving type information.\n */\nexport function jsonResource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>\n): Resource<Uri, Result> {\n return {\n uri,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource with a URI template while preserving type information.\n */\nexport function jsonResourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a list of resources that share a common URI scheme.\n */\nexport function resources<Scheme extends string>(\n scheme: Scheme,\n resources: (Resource | ResourceTemplate)[]\n): (\n | Resource<`${Scheme}://${string}`>\n | ResourceTemplate<`${Scheme}://${string}`>\n)[] {\n return resources.map((resource) => {\n if ('uri' in resource) {\n const url = new URL(resource.uri, `${scheme}://`);\n const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`;\n\n return {\n ...resource,\n uri,\n };\n }\n\n const url = new URL(resource.uriTemplate, `${scheme}://`);\n const uriTemplate = decodeURI(\n url.href\n ) as `${Scheme}://${typeof resource.uriTemplate}`;\n\n return {\n ...resource,\n uriTemplate,\n };\n });\n}\n\n/**\n * Helper function to create a JSON resource response.\n */\nexport function jsonResourceResponse<Uri extends string, Response>(\n uri: Uri,\n response: Response\n) {\n return {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(response),\n };\n}\n\n/**\n * Helper function to define an MCP tool while preserving type information.\n */\nexport function tool<\n Params extends z.ZodObject<any>,\n OutputSchema extends z.ZodObject<any>,\n>(tool: Tool<Params, OutputSchema>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n name: string;\n arguments: Record<string, unknown>;\n annotations?: Annotations;\n};\n\ntype ToolCallSuccessDetails = ToolCallBaseDetails & {\n success: true;\n data: unknown;\n};\n\ntype ToolCallErrorDetails = ToolCallBaseDetails & {\n success: false;\n error: unknown;\n};\n\nexport type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;\n\nexport type InitCallback = (initData: InitData) => void | Promise<void>;\nexport type ToolCallCallback = (details: ToolCallDetails) => void;\nexport type PropCallback<T> = () => T | Promise<T>;\nexport type Prop<T> = T | PropCallback<T>;\n\nexport type McpServerOptions = {\n /**\n * The name of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n name: string;\n\n /**\n * The title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Optional instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions?: string;\n\n /**\n * Callback for after a tool is called.\n */\n onToolCall?: ToolCallCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?: Prop<Record<string, Tool>>;\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer(options: McpServerOptions) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n instructions: options.instructions,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools() {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools()\n : options.tools;\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n 'resources/list',\n async (): Promise<ListResourcesResult> => {\n const allResources = await getResources();\n return {\n resources: allResources\n .filter((resource) => 'uri' in resource)\n .map(({ uri, name, description, mimeType }) => {\n return {\n uri,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n 'resources/templates/list',\n async (): Promise<ListResourceTemplatesResult> => {\n const allResources = await getResources();\n return {\n resourceTemplates: allResources\n .filter((resource) => 'uriTemplate' in resource)\n .map(({ uriTemplate, name, description, mimeType }) => {\n return {\n uriTemplate,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n 'resources/read',\n async (request): Promise<ReadResourceResult> => {\n try {\n const allResources = await getResources();\n const { uri } = request.params;\n\n const resources = allResources.filter(\n (resource) => 'uri' in resource\n );\n const resource = resources.find((resource) =>\n compareUris(resource.uri, uri)\n );\n\n if (resource) {\n const result = await resource.read(uri as `${string}://${string}`);\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n }\n\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceTemplateUris = resourceTemplates.map(\n ({ uriTemplate }) => assertValidUri(uriTemplate)\n );\n\n const templateMatch = matchUriTemplate(uri, resourceTemplateUris);\n\n if (!templateMatch) {\n throw new Error('resource not found');\n }\n\n const resourceTemplate = resourceTemplates.find(\n (r) => r.uriTemplate === templateMatch.uri\n );\n\n if (!resourceTemplate) {\n throw new Error('resource not found');\n }\n\n const result = await resourceTemplate.read(\n uri as `${string}://${string}`,\n templateMatch.params\n );\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n } catch (error) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } as any;\n }\n }\n );\n }\n\n if (options.tools) {\n server.setRequestHandler(\n 'tools/list',\n async (): Promise<ListToolsResult> => {\n const tools = await getTools();\n\n return {\n tools: await Promise.all(\n Object.entries(tools)\n .filter(([, tool]) => !tool.hidden)\n .map(async ([name, { description, annotations, parameters }]) => {\n const inputSchema = z.toJSONSchema(parameters, {\n target: 'draft-7',\n });\n\n return {\n name,\n description:\n typeof description === 'function'\n ? await description()\n : description,\n annotations,\n // Casting the same as the SDK does:\n // https://github.com/modelcontextprotocol/typescript-sdk/blob/fb07af810b51003c338dc4885a9e42f54519f9af/src/server/mcp.ts#L154\n inputSchema: inputSchema as McpTool['inputSchema'],\n };\n })\n ),\n } satisfies ListToolsResult;\n }\n );\n\n server.setRequestHandler('tools/call', async (request) => {\n try {\n const tools = await getTools();\n const toolName = request.params.name;\n\n if (!(toolName in tools)) {\n throw new Error('tool not found');\n }\n\n const tool = tools[toolName];\n\n if (!tool) {\n throw new Error('tool not found');\n }\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const executeWithCallback = async (tool: Tool) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n try {\n options.onToolCall?.({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\n });\n } catch (error) {\n // Don't fail the tool call if the callback fails\n console.error('Failed to run tool callback', error);\n }\n\n // Unwrap result\n if (!res.success) {\n throw res.error;\n }\n return res.data;\n };\n\n const result = await executeWithCallback(tool);\n\n const content =\n result != null\n ? [{ type: 'text' as const, text: JSON.stringify(result) }]\n : [];\n\n return {\n content,\n };\n } catch (error) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n };\n }\n });\n }\n\n return server;\n}\n\nfunction enumerateError(error: unknown) {\n if (!error) {\n return error;\n }\n\n if (typeof error !== 'object') {\n return error;\n }\n\n const newError: Record<string, unknown> = {};\n\n const errorProps = ['name', 'message'] as const;\n\n for (const prop of errorProps) {\n if (prop in error) {\n newError[prop] = (error as Record<string, unknown>)[prop];\n }\n }\n\n return newError;\n}\n","import type { ExtractParams } from './types.js';\n\n/**\n * Asserts that a URI is valid.\n */\nexport function assertValidUri(uri: string) {\n try {\n new URL(uri);\n return uri;\n } catch {\n throw new Error(`invalid uri: ${uri}`);\n }\n}\n\n/**\n * Compares two URIs.\n */\nexport function compareUris(uriA: string, uriB: string): boolean {\n const urlA = new URL(uriA);\n const urlB = new URL(uriB);\n\n return urlA.href === urlB.href;\n}\n\n/**\n * Matches a URI to a RFC 6570 URI Template (resourceUris) and extracts\n * the parameters.\n *\n * Currently only supports simple string parameters.\n */\nexport function matchUriTemplate<Templates extends string[]>(\n uri: string,\n uriTemplates: Templates\n):\n | {\n uri: Templates[number];\n params: { [Param in ExtractParams<Templates[number]>]: string };\n }\n | undefined {\n const url = new URL(uri);\n const segments = url.pathname.split('/').slice(1);\n\n for (const resourceUri of uriTemplates) {\n const resourceUrl = new URL(resourceUri);\n const resourceSegments = decodeURIComponent(resourceUrl.pathname)\n .split('/')\n .slice(1);\n\n if (segments.length !== resourceSegments.length) {\n continue;\n }\n\n const params: Record<string, string> = {};\n let isMatch = true;\n\n for (let i = 0; i < segments.length; i++) {\n const resourceSegment = resourceSegments[i];\n const segment = segments[i];\n\n if (!resourceSegment || !segment) {\n break;\n }\n\n if (resourceSegment.startsWith('{') && resourceSegment.endsWith('}')) {\n const paramKey = resourceSegment.slice(1, -1);\n\n if (!paramKey) {\n break;\n }\n\n params[paramKey] = segment;\n } else if (segments[i] !== resourceSegments[i]) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n return {\n uri: resourceUri,\n params: params as {\n [Param in ExtractParams<Templates[number]>]: string;\n },\n };\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/util.ts"],"names":["assertValidUri","uri"],"mappings":"AAAA,uuBAAyC,4BAcvB,SCTFA,CAAAA,CAAeC,CAAAA,CAAa,CAC1C,GAAI,CACF,OAAA,IAAI,GAAA,CAAIA,CAAG,CAAA,CACJA,CACT,CAAA,UAAQ,CACN,MAAM,IAAI,KAAA,CAAM,CAAA,aAAA,EAAgBA,CAAG,CAAA,CAAA","file":"/home/runner/work/mcp/mcp/packages/mcp-utils/dist/index.cjs","sourcesContent":["import { isCallToolResult, Server } from '@modelcontextprotocol/server';\nimport type {\n CallToolResult,\n ClientCapabilities,\n Implementation,\n InputRequiredResult,\n ListResourcesResult,\n ListResourceTemplatesResult,\n ListToolsResult,\n Tool as McpTool,\n ReadResourceResult,\n ServerCapabilities,\n ServerContext,\n} from '@modelcontextprotocol/server';\nimport { z } from 'zod/v4';\n\nimport type { ExtractParams } from './types.js';\nimport { assertValidUri, compareUris, matchUriTemplate } from './util.js';\n\nexport type Scheme = string;\nexport type Annotations = NonNullable<\n ListToolsResult['tools'][number]['annotations']\n>;\n\nexport type Resource<Uri extends string = string, Result = unknown> = {\n uri: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(uri: `${Scheme}://${Uri}`): Promise<Result>;\n};\n\nexport type ResourceTemplate<Uri extends string = string, Result = unknown> = {\n uriTemplate: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(\n uri: `${Scheme}://${Uri}`,\n params: {\n [Param in ExtractParams<Uri>]: string;\n }\n ): Promise<Result>;\n};\n\nexport type Tool<\n Params extends z.ZodObject<any> = z.ZodObject<any>,\n // MCP spec restricts outputSchema to type \"object\" at the root level:\n // https://modelcontextprotocol.io/specification/2025-11-25/schema#tool-outputschema\n OutputSchema extends z.ZodObject<any> = z.ZodObject<any>,\n> = {\n description: Prop<string>;\n annotations?: Annotations;\n parameters: Params;\n outputSchema: OutputSchema;\n /** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */\n hidden?: boolean;\n /**\n * Executes the tool. `ctx` is the SDK's per-request `ServerContext`\n * (elicitation, multi-round-trip `requestState`, HTTP info, etc.) — most\n * tools ignore it.\n *\n * Returning an `InputRequiredResult` or a direct `CallToolResult` is\n * passed straight to the client instead of being JSON-wrapped; any other\n * value is wrapped as today (`{ content: [{ type: 'text', text:\n * JSON.stringify(value) }] }`).\n */\n execute(\n params: z.infer<Params>,\n ctx: ServerContext\n ): Promise<z.infer<OutputSchema> | InputRequiredResult | CallToolResult>;\n};\n\n/**\n * Helper function to define an MCP resource while preserving type information.\n */\nexport function resource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri'>\n): Resource<Uri, Result> {\n return {\n uri,\n ...resource,\n };\n}\n\n/**\n * Helper function to define an MCP resource with a URI template while preserving type information.\n */\nexport function resourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource while preserving type information.\n */\nexport function jsonResource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>\n): Resource<Uri, Result> {\n return {\n uri,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource with a URI template while preserving type information.\n */\nexport function jsonResourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a list of resources that share a common URI scheme.\n */\nexport function resources<Scheme extends string>(\n scheme: Scheme,\n resources: (Resource | ResourceTemplate)[]\n): (\n | Resource<`${Scheme}://${string}`>\n | ResourceTemplate<`${Scheme}://${string}`>\n)[] {\n return resources.map((resource) => {\n if ('uri' in resource) {\n const url = new URL(resource.uri, `${scheme}://`);\n const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`;\n\n return {\n ...resource,\n uri,\n };\n }\n\n const url = new URL(resource.uriTemplate, `${scheme}://`);\n const uriTemplate = decodeURI(\n url.href\n ) as `${Scheme}://${typeof resource.uriTemplate}`;\n\n return {\n ...resource,\n uriTemplate,\n };\n });\n}\n\n/**\n * Helper function to create a JSON resource response.\n */\nexport function jsonResourceResponse<Uri extends string, Response>(\n uri: Uri,\n response: Response\n) {\n return {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(response),\n };\n}\n\n/**\n * Helper function to define an MCP tool while preserving type information.\n */\nexport function tool<\n Params extends z.ZodObject<any>,\n OutputSchema extends z.ZodObject<any>,\n>(tool: Tool<Params, OutputSchema>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n name: string;\n arguments: Record<string, unknown>;\n annotations?: Annotations;\n};\n\ntype ToolCallSuccessDetails = ToolCallBaseDetails & {\n success: true;\n data: unknown;\n};\n\ntype ToolCallErrorDetails = ToolCallBaseDetails & {\n success: false;\n error: unknown;\n};\n\nexport type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;\n\nexport type InitCallback = (initData: InitData) => void | Promise<void>;\nexport type ToolCallCallback = (details: ToolCallDetails) => void;\nexport type PropCallback<T> = () => T | Promise<T>;\nexport type Prop<T> = T | PropCallback<T>;\n\nexport type McpServerOptions = {\n /**\n * The name of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n name: string;\n\n /**\n * The title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Optional instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions?: string;\n\n /**\n * Callback for after a tool is called.\n */\n onToolCall?: ToolCallCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?:\n | Record<string, Tool>\n | ((\n ctx?: ServerContext\n ) => Record<string, Tool> | Promise<Record<string, Tool>>);\n\n /**\n * Multi-round-trip `requestState` integrity hook (protocol revision\n * 2026-07-28), passed straight through to the underlying SDK `Server`.\n *\n * Configure this with `createRequestStateCodec`'s `verify` to\n * authenticate `requestState` a tool mints via `inputRequired(...)`.\n * Leaving it unset keeps the SDK's passthrough behavior.\n */\n requestState?: {\n verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;\n };\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer(options: McpServerOptions) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n instructions: options.instructions,\n requestState: options.requestState,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools(ctx?: ServerContext) {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools(ctx)\n : options.tools;\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n 'resources/list',\n async (): Promise<ListResourcesResult> => {\n const allResources = await getResources();\n return {\n resources: allResources\n .filter((resource) => 'uri' in resource)\n .map(({ uri, name, description, mimeType }) => {\n return {\n uri,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n 'resources/templates/list',\n async (): Promise<ListResourceTemplatesResult> => {\n const allResources = await getResources();\n return {\n resourceTemplates: allResources\n .filter((resource) => 'uriTemplate' in resource)\n .map(({ uriTemplate, name, description, mimeType }) => {\n return {\n uriTemplate,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n 'resources/read',\n async (request): Promise<ReadResourceResult> => {\n try {\n const allResources = await getResources();\n const { uri } = request.params;\n\n const resources = allResources.filter(\n (resource) => 'uri' in resource\n );\n const resource = resources.find((resource) =>\n compareUris(resource.uri, uri)\n );\n\n if (resource) {\n const result = await resource.read(uri as `${string}://${string}`);\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n }\n\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceTemplateUris = resourceTemplates.map(\n ({ uriTemplate }) => assertValidUri(uriTemplate)\n );\n\n const templateMatch = matchUriTemplate(uri, resourceTemplateUris);\n\n if (!templateMatch) {\n throw new Error('resource not found');\n }\n\n const resourceTemplate = resourceTemplates.find(\n (r) => r.uriTemplate === templateMatch.uri\n );\n\n if (!resourceTemplate) {\n throw new Error('resource not found');\n }\n\n const result = await resourceTemplate.read(\n uri as `${string}://${string}`,\n templateMatch.params\n );\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n } catch (error) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } as any;\n }\n }\n );\n }\n\n if (options.tools) {\n server.setRequestHandler(\n 'tools/list',\n async (_request, ctx): Promise<ListToolsResult> => {\n const tools = await getTools(ctx);\n\n return {\n tools: await Promise.all(\n Object.entries(tools)\n .filter(([, tool]) => !tool.hidden)\n .map(async ([name, { description, annotations, parameters }]) => {\n const inputSchema = z.toJSONSchema(parameters, {\n target: 'draft-7',\n });\n\n return {\n name,\n description:\n typeof description === 'function'\n ? await description()\n : description,\n annotations,\n // Casting the same as the SDK does:\n // https://github.com/modelcontextprotocol/typescript-sdk/blob/fb07af810b51003c338dc4885a9e42f54519f9af/src/server/mcp.ts#L154\n inputSchema: inputSchema as McpTool['inputSchema'],\n };\n })\n ),\n } satisfies ListToolsResult;\n }\n );\n\n server.setRequestHandler('tools/call', async (request, ctx) => {\n try {\n const tools = await getTools(ctx);\n const toolName = request.params.name;\n\n if (!(toolName in tools)) {\n throw new Error('tool not found');\n }\n\n const tool = tools[toolName];\n\n if (!tool) {\n throw new Error('tool not found');\n }\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const executeWithCallback = async (tool: Tool) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args, ctx)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n try {\n options.onToolCall?.({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\n });\n } catch (error) {\n // Don't fail the tool call if the callback fails\n console.error('Failed to run tool callback', error);\n }\n\n // Unwrap result\n if (!res.success) {\n throw res.error;\n }\n return res.data;\n };\n\n const result = await executeWithCallback(tool);\n\n // An InputRequiredResult or a direct CallToolResult is already\n // shaped for the wire; pass it through instead of JSON-wrapping it.\n if (isInputRequiredResult(result) || isCallToolResult(result)) {\n return result;\n }\n\n const content =\n result != null\n ? [{ type: 'text' as const, text: JSON.stringify(result) }]\n : [];\n\n return {\n content,\n };\n } catch (error) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n };\n }\n });\n }\n\n return server;\n}\n\nfunction isInputRequiredResult(value: unknown): value is InputRequiredResult {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { resultType?: unknown }).resultType === 'input_required'\n );\n}\n\nfunction enumerateError(error: unknown) {\n if (!error) {\n return error;\n }\n\n if (typeof error !== 'object') {\n return error;\n }\n\n const newError: Record<string, unknown> = {};\n\n const errorProps = ['name', 'message'] as const;\n\n for (const prop of errorProps) {\n if (prop in error) {\n newError[prop] = (error as Record<string, unknown>)[prop];\n }\n }\n\n return newError;\n}\n","import type { ExtractParams } from './types.js';\n\n/**\n * Asserts that a URI is valid.\n */\nexport function assertValidUri(uri: string) {\n try {\n new URL(uri);\n return uri;\n } catch {\n throw new Error(`invalid uri: ${uri}`);\n }\n}\n\n/**\n * Compares two URIs.\n */\nexport function compareUris(uriA: string, uriB: string): boolean {\n const urlA = new URL(uriA);\n const urlB = new URL(uriB);\n\n return urlA.href === urlB.href;\n}\n\n/**\n * Matches a URI to a RFC 6570 URI Template (resourceUris) and extracts\n * the parameters.\n *\n * Currently only supports simple string parameters.\n */\nexport function matchUriTemplate<Templates extends string[]>(\n uri: string,\n uriTemplates: Templates\n):\n | {\n uri: Templates[number];\n params: { [Param in ExtractParams<Templates[number]>]: string };\n }\n | undefined {\n const url = new URL(uri);\n const segments = url.pathname.split('/').slice(1);\n\n for (const resourceUri of uriTemplates) {\n const resourceUrl = new URL(resourceUri);\n const resourceSegments = decodeURIComponent(resourceUrl.pathname)\n .split('/')\n .slice(1);\n\n if (segments.length !== resourceSegments.length) {\n continue;\n }\n\n const params: Record<string, string> = {};\n let isMatch = true;\n\n for (let i = 0; i < segments.length; i++) {\n const resourceSegment = resourceSegments[i];\n const segment = segments[i];\n\n if (!resourceSegment || !segment) {\n break;\n }\n\n if (resourceSegment.startsWith('{') && resourceSegment.endsWith('}')) {\n const paramKey = resourceSegment.slice(1, -1);\n\n if (!paramKey) {\n break;\n }\n\n params[paramKey] = segment;\n } else if (segments[i] !== resourceSegments[i]) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n return {\n uri: resourceUri,\n params: params as {\n [Param in ExtractParams<Templates[number]>]: string;\n },\n };\n }\n }\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ListToolsResult, Implementation, ClientCapabilities, Server, Transport, JSONRPCMessage } from '@modelcontextprotocol/server';
|
|
1
|
+
import { ListToolsResult, ServerContext, InputRequiredResult, CallToolResult, Implementation, ClientCapabilities, Server, Transport, JSONRPCMessage } from '@modelcontextprotocol/server';
|
|
2
2
|
import { z } from 'zod/v4';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -42,7 +42,17 @@ type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema exten
|
|
|
42
42
|
outputSchema: OutputSchema;
|
|
43
43
|
/** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */
|
|
44
44
|
hidden?: boolean;
|
|
45
|
-
|
|
45
|
+
/**
|
|
46
|
+
* Executes the tool. `ctx` is the SDK's per-request `ServerContext`
|
|
47
|
+
* (elicitation, multi-round-trip `requestState`, HTTP info, etc.) — most
|
|
48
|
+
* tools ignore it.
|
|
49
|
+
*
|
|
50
|
+
* Returning an `InputRequiredResult` or a direct `CallToolResult` is
|
|
51
|
+
* passed straight to the client instead of being JSON-wrapped; any other
|
|
52
|
+
* value is wrapped as today (`{ content: [{ type: 'text', text:
|
|
53
|
+
* JSON.stringify(value) }] }`).
|
|
54
|
+
*/
|
|
55
|
+
execute(params: z.infer<Params>, ctx: ServerContext): Promise<z.infer<OutputSchema> | InputRequiredResult | CallToolResult>;
|
|
46
56
|
};
|
|
47
57
|
/**
|
|
48
58
|
* Helper function to define an MCP resource while preserving type information.
|
|
@@ -151,7 +161,18 @@ type McpServerOptions = {
|
|
|
151
161
|
* asks for the list of tools or invokes a tool. This allows for dynamic tools
|
|
152
162
|
* that can change after the server has started.
|
|
153
163
|
*/
|
|
154
|
-
tools?:
|
|
164
|
+
tools?: Record<string, Tool> | ((ctx?: ServerContext) => Record<string, Tool> | Promise<Record<string, Tool>>);
|
|
165
|
+
/**
|
|
166
|
+
* Multi-round-trip `requestState` integrity hook (protocol revision
|
|
167
|
+
* 2026-07-28), passed straight through to the underlying SDK `Server`.
|
|
168
|
+
*
|
|
169
|
+
* Configure this with `createRequestStateCodec`'s `verify` to
|
|
170
|
+
* authenticate `requestState` a tool mints via `inputRequired(...)`.
|
|
171
|
+
* Leaving it unset keeps the SDK's passthrough behavior.
|
|
172
|
+
*/
|
|
173
|
+
requestState?: {
|
|
174
|
+
verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;
|
|
175
|
+
};
|
|
155
176
|
};
|
|
156
177
|
/**
|
|
157
178
|
* Creates an MCP server with the given options.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ListToolsResult, Implementation, ClientCapabilities, Server, Transport, JSONRPCMessage } from '@modelcontextprotocol/server';
|
|
1
|
+
import { ListToolsResult, ServerContext, InputRequiredResult, CallToolResult, Implementation, ClientCapabilities, Server, Transport, JSONRPCMessage } from '@modelcontextprotocol/server';
|
|
2
2
|
import { z } from 'zod/v4';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -42,7 +42,17 @@ type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema exten
|
|
|
42
42
|
outputSchema: OutputSchema;
|
|
43
43
|
/** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */
|
|
44
44
|
hidden?: boolean;
|
|
45
|
-
|
|
45
|
+
/**
|
|
46
|
+
* Executes the tool. `ctx` is the SDK's per-request `ServerContext`
|
|
47
|
+
* (elicitation, multi-round-trip `requestState`, HTTP info, etc.) — most
|
|
48
|
+
* tools ignore it.
|
|
49
|
+
*
|
|
50
|
+
* Returning an `InputRequiredResult` or a direct `CallToolResult` is
|
|
51
|
+
* passed straight to the client instead of being JSON-wrapped; any other
|
|
52
|
+
* value is wrapped as today (`{ content: [{ type: 'text', text:
|
|
53
|
+
* JSON.stringify(value) }] }`).
|
|
54
|
+
*/
|
|
55
|
+
execute(params: z.infer<Params>, ctx: ServerContext): Promise<z.infer<OutputSchema> | InputRequiredResult | CallToolResult>;
|
|
46
56
|
};
|
|
47
57
|
/**
|
|
48
58
|
* Helper function to define an MCP resource while preserving type information.
|
|
@@ -151,7 +161,18 @@ type McpServerOptions = {
|
|
|
151
161
|
* asks for the list of tools or invokes a tool. This allows for dynamic tools
|
|
152
162
|
* that can change after the server has started.
|
|
153
163
|
*/
|
|
154
|
-
tools?:
|
|
164
|
+
tools?: Record<string, Tool> | ((ctx?: ServerContext) => Record<string, Tool> | Promise<Record<string, Tool>>);
|
|
165
|
+
/**
|
|
166
|
+
* Multi-round-trip `requestState` integrity hook (protocol revision
|
|
167
|
+
* 2026-07-28), passed straight through to the underlying SDK `Server`.
|
|
168
|
+
*
|
|
169
|
+
* Configure this with `createRequestStateCodec`'s `verify` to
|
|
170
|
+
* authenticate `requestState` a tool mints via `inputRequired(...)`.
|
|
171
|
+
* Leaving it unset keeps the SDK's passthrough behavior.
|
|
172
|
+
*/
|
|
173
|
+
requestState?: {
|
|
174
|
+
verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;
|
|
175
|
+
};
|
|
155
176
|
};
|
|
156
177
|
/**
|
|
157
178
|
* Creates an MCP server with the given options.
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Server as b}from"@modelcontextprotocol/server";import{z as
|
|
1
|
+
import{isCallToolResult as S,Server as b}from"@modelcontextprotocol/server";import{z as C}from"zod/v4";function g(e){try{return new URL(e),e}catch{throw new Error(`invalid uri: ${e}`)}}function T(e,t){let o=new URL(e),l=new URL(t);return o.href===l.href}function w(e,t){let l=new URL(e).pathname.split("/").slice(1);for(let p of t){let r=new URL(p),s=decodeURIComponent(r.pathname).split("/").slice(1);if(l.length!==s.length)continue;let a={},c=!0;for(let n=0;n<l.length;n++){let m=s[n],R=l[n];if(!m||!R)break;if(m.startsWith("{")&&m.endsWith("}")){let u=m.slice(1,-1);if(!u)break;a[u]=R}else if(l[n]!==s[n]){c=!1;break}}if(c)return{uri:p,params:a}}}function $(e,t){return{uri:e,...t}}function j(e,t){return{uriTemplate:e,...t}}function D(e,t){return{uri:e,mimeType:"application/json",...t}}function I(e,t){return{uriTemplate:e,mimeType:"application/json",...t}}function z(e,t){return t.map(o=>{if("uri"in o){let r=new URL(o.uri,`${e}://`),s=decodeURI(r.href);return{...o,uri:s}}let l=new URL(o.uriTemplate,`${e}://`),p=decodeURI(l.href);return{...o,uriTemplate:p}})}function L(e,t){return{uri:e,mimeType:"application/json",text:JSON.stringify(t)}}function N(e){return e}function q(e){let t={};e.resources&&(t.resources={}),e.tools&&(t.tools={});let o=new b({name:e.name,title:e.title,version:e.version},{capabilities:t,instructions:e.instructions,requestState:e.requestState});async function l(){if(!e.resources)throw new Error("resources not available");return typeof e.resources=="function"?await e.resources():e.resources}async function p(r){if(!e.tools)throw new Error("tools not available");return typeof e.tools=="function"?await e.tools(r):e.tools}return o.oninitialized=async()=>{let r=o.getClientVersion(),s=o.getClientCapabilities();if(!r)throw new Error("client info not available after initialization");if(!s)throw new Error("client capabilities not available after initialization");let a={clientInfo:r,clientCapabilities:s};await e.onInitialize?.(a)},e.resources&&(o.setRequestHandler("resources/list",async()=>({resources:(await l()).filter(s=>"uri"in s).map(({uri:s,name:a,description:c,mimeType:n})=>({uri:s,name:a,description:c,mimeType:n}))})),o.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:(await l()).filter(s=>"uriTemplate"in s).map(({uriTemplate:s,name:a,description:c,mimeType:n})=>({uriTemplate:s,name:a,description:c,mimeType:n}))})),o.setRequestHandler("resources/read",async r=>{try{let s=await l(),{uri:a}=r.params,n=s.filter(i=>"uri"in i).find(i=>T(i.uri,a));if(n){let i=await n.read(a);return{contents:Array.isArray(i)?i:[i]}}let m=s.filter(i=>"uriTemplate"in i),R=m.map(({uriTemplate:i})=>g(i)),u=w(a,R);if(!u)throw new Error("resource not found");let y=m.find(i=>i.uriTemplate===u.uri);if(!y)throw new Error("resource not found");let d=await y.read(a,u.params);return{contents:Array.isArray(d)?d:[d]}}catch(s){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:h(s)})}]}}})),e.tools&&(o.setRequestHandler("tools/list",async(r,s)=>{let a=await p(s);return{tools:await Promise.all(Object.entries(a).filter(([,c])=>!c.hidden).map(async([c,{description:n,annotations:m,parameters:R}])=>{let u=C.toJSONSchema(R,{target:"draft-7"});return{name:c,description:typeof n=="function"?await n():n,annotations:m,inputSchema:u}}))}}),o.setRequestHandler("tools/call",async(r,s)=>{try{let a=await p(s),c=r.params.name;if(!(c in a))throw new Error("tool not found");let n=a[c];if(!n)throw new Error("tool not found");let m=n.parameters.strict().parse(r.params.arguments??{}),u=await(async d=>{let f=await d.execute(m,s).then(i=>({success:!0,data:i})).catch(i=>({success:!1,error:i}));try{e.onToolCall?.({name:c,arguments:m,annotations:d.annotations,...f})}catch(i){console.error("Failed to run tool callback",i)}if(!f.success)throw f.error;return f.data})(n);return U(u)||S(u)?u:{content:u!=null?[{type:"text",text:JSON.stringify(u)}]:[]}}catch(a){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:h(a)})}]}}})),o}function U(e){return typeof e=="object"&&e!==null&&e.resultType==="input_required"}function h(e){if(!e||typeof e!="object")return e;let t={},o=["name","message"];for(let l of o)l in e&&(t[l]=e[l]);return t}var x=class{#e;#t;ready;readable;writable;onclose;onerror;onmessage;constructor(){let t,o,l=new Promise(r=>{t=r}),p=new Promise(r=>{o=r});this.ready=Promise.all([l,p]).then(()=>{}),this.readable=new ReadableStream({start:r=>{this.#e=r,t()}}),this.writable=new WritableStream({start:r=>{this.#t=r,o()},write:r=>{this.onmessage?.(r)}})}async start(){await this.ready}async send(t){if(!this.#e)throw new Error("readable stream not initialized");this.#e.enqueue(t)}async close(){this.#e?.error(new Error("connection closed")),this.#t?.error(new Error("connection closed")),this.onclose?.()}};export{x as StreamTransport,q as createMcpServer,D as jsonResource,L as jsonResourceResponse,I as jsonResourceTemplate,$ as resource,j as resourceTemplate,z as resources,N as tool};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/util.ts","../src/stream-transport.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/server';\nimport type {\n ClientCapabilities,\n Implementation,\n ListResourcesResult,\n ListResourceTemplatesResult,\n ListToolsResult,\n Tool as McpTool,\n ReadResourceResult,\n ServerCapabilities,\n} from '@modelcontextprotocol/server';\nimport { z } from 'zod/v4';\n\nimport type { ExtractParams } from './types.js';\nimport { assertValidUri, compareUris, matchUriTemplate } from './util.js';\n\nexport type Scheme = string;\nexport type Annotations = NonNullable<\n ListToolsResult['tools'][number]['annotations']\n>;\n\nexport type Resource<Uri extends string = string, Result = unknown> = {\n uri: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(uri: `${Scheme}://${Uri}`): Promise<Result>;\n};\n\nexport type ResourceTemplate<Uri extends string = string, Result = unknown> = {\n uriTemplate: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(\n uri: `${Scheme}://${Uri}`,\n params: {\n [Param in ExtractParams<Uri>]: string;\n }\n ): Promise<Result>;\n};\n\nexport type Tool<\n Params extends z.ZodObject<any> = z.ZodObject<any>,\n // MCP spec restricts outputSchema to type \"object\" at the root level:\n // https://modelcontextprotocol.io/specification/2025-11-25/schema#tool-outputschema\n OutputSchema extends z.ZodObject<any> = z.ZodObject<any>,\n> = {\n description: Prop<string>;\n annotations?: Annotations;\n parameters: Params;\n outputSchema: OutputSchema;\n /** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */\n hidden?: boolean;\n execute(params: z.infer<Params>): Promise<z.infer<OutputSchema>>;\n};\n\n/**\n * Helper function to define an MCP resource while preserving type information.\n */\nexport function resource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri'>\n): Resource<Uri, Result> {\n return {\n uri,\n ...resource,\n };\n}\n\n/**\n * Helper function to define an MCP resource with a URI template while preserving type information.\n */\nexport function resourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource while preserving type information.\n */\nexport function jsonResource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>\n): Resource<Uri, Result> {\n return {\n uri,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource with a URI template while preserving type information.\n */\nexport function jsonResourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a list of resources that share a common URI scheme.\n */\nexport function resources<Scheme extends string>(\n scheme: Scheme,\n resources: (Resource | ResourceTemplate)[]\n): (\n | Resource<`${Scheme}://${string}`>\n | ResourceTemplate<`${Scheme}://${string}`>\n)[] {\n return resources.map((resource) => {\n if ('uri' in resource) {\n const url = new URL(resource.uri, `${scheme}://`);\n const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`;\n\n return {\n ...resource,\n uri,\n };\n }\n\n const url = new URL(resource.uriTemplate, `${scheme}://`);\n const uriTemplate = decodeURI(\n url.href\n ) as `${Scheme}://${typeof resource.uriTemplate}`;\n\n return {\n ...resource,\n uriTemplate,\n };\n });\n}\n\n/**\n * Helper function to create a JSON resource response.\n */\nexport function jsonResourceResponse<Uri extends string, Response>(\n uri: Uri,\n response: Response\n) {\n return {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(response),\n };\n}\n\n/**\n * Helper function to define an MCP tool while preserving type information.\n */\nexport function tool<\n Params extends z.ZodObject<any>,\n OutputSchema extends z.ZodObject<any>,\n>(tool: Tool<Params, OutputSchema>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n name: string;\n arguments: Record<string, unknown>;\n annotations?: Annotations;\n};\n\ntype ToolCallSuccessDetails = ToolCallBaseDetails & {\n success: true;\n data: unknown;\n};\n\ntype ToolCallErrorDetails = ToolCallBaseDetails & {\n success: false;\n error: unknown;\n};\n\nexport type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;\n\nexport type InitCallback = (initData: InitData) => void | Promise<void>;\nexport type ToolCallCallback = (details: ToolCallDetails) => void;\nexport type PropCallback<T> = () => T | Promise<T>;\nexport type Prop<T> = T | PropCallback<T>;\n\nexport type McpServerOptions = {\n /**\n * The name of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n name: string;\n\n /**\n * The title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Optional instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions?: string;\n\n /**\n * Callback for after a tool is called.\n */\n onToolCall?: ToolCallCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?: Prop<Record<string, Tool>>;\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer(options: McpServerOptions) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n instructions: options.instructions,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools() {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools()\n : options.tools;\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n 'resources/list',\n async (): Promise<ListResourcesResult> => {\n const allResources = await getResources();\n return {\n resources: allResources\n .filter((resource) => 'uri' in resource)\n .map(({ uri, name, description, mimeType }) => {\n return {\n uri,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n 'resources/templates/list',\n async (): Promise<ListResourceTemplatesResult> => {\n const allResources = await getResources();\n return {\n resourceTemplates: allResources\n .filter((resource) => 'uriTemplate' in resource)\n .map(({ uriTemplate, name, description, mimeType }) => {\n return {\n uriTemplate,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n 'resources/read',\n async (request): Promise<ReadResourceResult> => {\n try {\n const allResources = await getResources();\n const { uri } = request.params;\n\n const resources = allResources.filter(\n (resource) => 'uri' in resource\n );\n const resource = resources.find((resource) =>\n compareUris(resource.uri, uri)\n );\n\n if (resource) {\n const result = await resource.read(uri as `${string}://${string}`);\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n }\n\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceTemplateUris = resourceTemplates.map(\n ({ uriTemplate }) => assertValidUri(uriTemplate)\n );\n\n const templateMatch = matchUriTemplate(uri, resourceTemplateUris);\n\n if (!templateMatch) {\n throw new Error('resource not found');\n }\n\n const resourceTemplate = resourceTemplates.find(\n (r) => r.uriTemplate === templateMatch.uri\n );\n\n if (!resourceTemplate) {\n throw new Error('resource not found');\n }\n\n const result = await resourceTemplate.read(\n uri as `${string}://${string}`,\n templateMatch.params\n );\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n } catch (error) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } as any;\n }\n }\n );\n }\n\n if (options.tools) {\n server.setRequestHandler(\n 'tools/list',\n async (): Promise<ListToolsResult> => {\n const tools = await getTools();\n\n return {\n tools: await Promise.all(\n Object.entries(tools)\n .filter(([, tool]) => !tool.hidden)\n .map(async ([name, { description, annotations, parameters }]) => {\n const inputSchema = z.toJSONSchema(parameters, {\n target: 'draft-7',\n });\n\n return {\n name,\n description:\n typeof description === 'function'\n ? await description()\n : description,\n annotations,\n // Casting the same as the SDK does:\n // https://github.com/modelcontextprotocol/typescript-sdk/blob/fb07af810b51003c338dc4885a9e42f54519f9af/src/server/mcp.ts#L154\n inputSchema: inputSchema as McpTool['inputSchema'],\n };\n })\n ),\n } satisfies ListToolsResult;\n }\n );\n\n server.setRequestHandler('tools/call', async (request) => {\n try {\n const tools = await getTools();\n const toolName = request.params.name;\n\n if (!(toolName in tools)) {\n throw new Error('tool not found');\n }\n\n const tool = tools[toolName];\n\n if (!tool) {\n throw new Error('tool not found');\n }\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const executeWithCallback = async (tool: Tool) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n try {\n options.onToolCall?.({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\n });\n } catch (error) {\n // Don't fail the tool call if the callback fails\n console.error('Failed to run tool callback', error);\n }\n\n // Unwrap result\n if (!res.success) {\n throw res.error;\n }\n return res.data;\n };\n\n const result = await executeWithCallback(tool);\n\n const content =\n result != null\n ? [{ type: 'text' as const, text: JSON.stringify(result) }]\n : [];\n\n return {\n content,\n };\n } catch (error) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n };\n }\n });\n }\n\n return server;\n}\n\nfunction enumerateError(error: unknown) {\n if (!error) {\n return error;\n }\n\n if (typeof error !== 'object') {\n return error;\n }\n\n const newError: Record<string, unknown> = {};\n\n const errorProps = ['name', 'message'] as const;\n\n for (const prop of errorProps) {\n if (prop in error) {\n newError[prop] = (error as Record<string, unknown>)[prop];\n }\n }\n\n return newError;\n}\n","import type { ExtractParams } from './types.js';\n\n/**\n * Asserts that a URI is valid.\n */\nexport function assertValidUri(uri: string) {\n try {\n new URL(uri);\n return uri;\n } catch {\n throw new Error(`invalid uri: ${uri}`);\n }\n}\n\n/**\n * Compares two URIs.\n */\nexport function compareUris(uriA: string, uriB: string): boolean {\n const urlA = new URL(uriA);\n const urlB = new URL(uriB);\n\n return urlA.href === urlB.href;\n}\n\n/**\n * Matches a URI to a RFC 6570 URI Template (resourceUris) and extracts\n * the parameters.\n *\n * Currently only supports simple string parameters.\n */\nexport function matchUriTemplate<Templates extends string[]>(\n uri: string,\n uriTemplates: Templates\n):\n | {\n uri: Templates[number];\n params: { [Param in ExtractParams<Templates[number]>]: string };\n }\n | undefined {\n const url = new URL(uri);\n const segments = url.pathname.split('/').slice(1);\n\n for (const resourceUri of uriTemplates) {\n const resourceUrl = new URL(resourceUri);\n const resourceSegments = decodeURIComponent(resourceUrl.pathname)\n .split('/')\n .slice(1);\n\n if (segments.length !== resourceSegments.length) {\n continue;\n }\n\n const params: Record<string, string> = {};\n let isMatch = true;\n\n for (let i = 0; i < segments.length; i++) {\n const resourceSegment = resourceSegments[i];\n const segment = segments[i];\n\n if (!resourceSegment || !segment) {\n break;\n }\n\n if (resourceSegment.startsWith('{') && resourceSegment.endsWith('}')) {\n const paramKey = resourceSegment.slice(1, -1);\n\n if (!paramKey) {\n break;\n }\n\n params[paramKey] = segment;\n } else if (segments[i] !== resourceSegments[i]) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n return {\n uri: resourceUri,\n params: params as {\n [Param in ExtractParams<Templates[number]>]: string;\n },\n };\n }\n }\n}\n","import type { JSONRPCMessage, Transport } from '@modelcontextprotocol/server';\n\nimport type { DuplexStream } from './types.js';\n\n/**\n * An MCP transport built on top of a duplex stream.\n * It uses a `ReadableStream` to receive messages and a `WritableStream` to send messages.\n *\n * Useful if you wish to pipe messages over your own stream-based transport or directly between two streams.\n */\nexport class StreamTransport\n implements Transport, DuplexStream<JSONRPCMessage>\n{\n #readableStreamController?: ReadableStreamDefaultController<JSONRPCMessage>;\n #writeableStreamController?: WritableStreamDefaultController;\n\n ready: Promise<void>;\n\n readable: ReadableStream<JSONRPCMessage>;\n writable: WritableStream<JSONRPCMessage>;\n\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n\n constructor() {\n let resolveReadReady: () => void;\n let resolveWriteReady: () => void;\n\n const readReady = new Promise<void>((resolve) => {\n resolveReadReady = resolve;\n });\n\n const writeReady = new Promise<void>((resolve) => {\n resolveWriteReady = resolve;\n });\n\n this.ready = Promise.all([readReady, writeReady]).then(() => {});\n\n this.readable = new ReadableStream({\n start: (controller) => {\n this.#readableStreamController = controller;\n resolveReadReady();\n },\n });\n\n this.writable = new WritableStream({\n start: (controller) => {\n this.#writeableStreamController = controller;\n resolveWriteReady();\n },\n write: (message) => {\n this.onmessage?.(message);\n },\n });\n }\n\n async start() {\n await this.ready;\n }\n\n async send(message: JSONRPCMessage) {\n if (!this.#readableStreamController) {\n throw new Error('readable stream not initialized');\n }\n this.#readableStreamController.enqueue(message);\n }\n\n async close() {\n this.#readableStreamController?.error(new Error('connection closed'));\n this.#writeableStreamController?.error(new Error('connection closed'));\n this.onclose?.();\n }\n}\n"],"mappings":"AAAA,OAAS,UAAAA,MAAc,+BAWvB,OAAS,KAAAC,MAAS,SCNX,SAASC,EAAeC,EAAa,CAC1C,GAAI,CACF,WAAI,IAAIA,CAAG,EACJA,CACT,MAAQ,CACN,MAAM,IAAI,MAAM,gBAAgBA,CAAG,EAAE,CACvC,CACF,CAKO,SAASC,EAAYC,EAAcC,EAAuB,CAC/D,IAAMC,EAAO,IAAI,IAAIF,CAAI,EACnBG,EAAO,IAAI,IAAIF,CAAI,EAEzB,OAAOC,EAAK,OAASC,EAAK,IAC5B,CAQO,SAASC,EACdN,EACAO,EAMY,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EAAE,KAAK,IAAM,CAAC,CAAC,EAE/D,KAAK,SAAW,IAAI,eAAe,CACjC,MAAQC,GAAe,CACrB,KAAKP,GAA4BO,EACjCL,EAAiB,CACnB,CACF,CAAC,EAED,KAAK,SAAW,IAAI,eAAe,CACjC,MAAQK,GAAe,CACrB,KAAKN,GAA6BM,EAClCJ,EAAkB,CACpB,EACA,MAAQK,GAAY,CAClB,KAAK,YAAYA,CAAO,CAC1B,CACF,CAAC,CACH,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,KACb,CAEA,MAAM,KAAKA,EAAyB,CAClC,GAAI,CAAC,KAAKR,GACR,MAAM,IAAI,MAAM,iCAAiC,EAEnD,KAAKA,GAA0B,QAAQQ,CAAO,CAChD,CAEA,MAAM,OAAQ,CACZ,KAAKR,IAA2B,MAAM,IAAI,MAAM,mBAAmB,CAAC,EACpE,KAAKC,IAA4B,MAAM,IAAI,MAAM,mBAAmB,CAAC,EACrE,KAAK,UAAU,CACjB,CACF","names":["Server","z","assertValidUri","uri","compareUris","uriA","uriB","urlA","urlB","matchUriTemplate","uriTemplates","segments","resourceUri","resourceUrl","resourceSegments","params","isMatch","resourceSegment","segment","paramKey","resource","uri","resourceTemplate","uriTemplate","jsonResource","jsonResourceTemplate","resources","scheme","url","jsonResourceResponse","response","tool","createMcpServer","options","capabilities","server","Server","getResources","getTools","clientInfo","clientCapabilities","initData","name","description","mimeType","request","allResources","compareUris","result","resourceTemplates","resourceTemplateUris","assertValidUri","templateMatch","matchUriTemplate","r","error","enumerateError","tools","annotations","parameters","inputSchema","z","toolName","args","res","data","newError","errorProps","prop","StreamTransport","#readableStreamController","#writeableStreamController","resolveReadReady","resolveWriteReady","readReady","resolve","writeReady","controller","message"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/util.ts","../src/stream-transport.ts"],"sourcesContent":["import { isCallToolResult, Server } from '@modelcontextprotocol/server';\nimport type {\n CallToolResult,\n ClientCapabilities,\n Implementation,\n InputRequiredResult,\n ListResourcesResult,\n ListResourceTemplatesResult,\n ListToolsResult,\n Tool as McpTool,\n ReadResourceResult,\n ServerCapabilities,\n ServerContext,\n} from '@modelcontextprotocol/server';\nimport { z } from 'zod/v4';\n\nimport type { ExtractParams } from './types.js';\nimport { assertValidUri, compareUris, matchUriTemplate } from './util.js';\n\nexport type Scheme = string;\nexport type Annotations = NonNullable<\n ListToolsResult['tools'][number]['annotations']\n>;\n\nexport type Resource<Uri extends string = string, Result = unknown> = {\n uri: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(uri: `${Scheme}://${Uri}`): Promise<Result>;\n};\n\nexport type ResourceTemplate<Uri extends string = string, Result = unknown> = {\n uriTemplate: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(\n uri: `${Scheme}://${Uri}`,\n params: {\n [Param in ExtractParams<Uri>]: string;\n }\n ): Promise<Result>;\n};\n\nexport type Tool<\n Params extends z.ZodObject<any> = z.ZodObject<any>,\n // MCP spec restricts outputSchema to type \"object\" at the root level:\n // https://modelcontextprotocol.io/specification/2025-11-25/schema#tool-outputschema\n OutputSchema extends z.ZodObject<any> = z.ZodObject<any>,\n> = {\n description: Prop<string>;\n annotations?: Annotations;\n parameters: Params;\n outputSchema: OutputSchema;\n /** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */\n hidden?: boolean;\n /**\n * Executes the tool. `ctx` is the SDK's per-request `ServerContext`\n * (elicitation, multi-round-trip `requestState`, HTTP info, etc.) — most\n * tools ignore it.\n *\n * Returning an `InputRequiredResult` or a direct `CallToolResult` is\n * passed straight to the client instead of being JSON-wrapped; any other\n * value is wrapped as today (`{ content: [{ type: 'text', text:\n * JSON.stringify(value) }] }`).\n */\n execute(\n params: z.infer<Params>,\n ctx: ServerContext\n ): Promise<z.infer<OutputSchema> | InputRequiredResult | CallToolResult>;\n};\n\n/**\n * Helper function to define an MCP resource while preserving type information.\n */\nexport function resource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri'>\n): Resource<Uri, Result> {\n return {\n uri,\n ...resource,\n };\n}\n\n/**\n * Helper function to define an MCP resource with a URI template while preserving type information.\n */\nexport function resourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource while preserving type information.\n */\nexport function jsonResource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>\n): Resource<Uri, Result> {\n return {\n uri,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource with a URI template while preserving type information.\n */\nexport function jsonResourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a list of resources that share a common URI scheme.\n */\nexport function resources<Scheme extends string>(\n scheme: Scheme,\n resources: (Resource | ResourceTemplate)[]\n): (\n | Resource<`${Scheme}://${string}`>\n | ResourceTemplate<`${Scheme}://${string}`>\n)[] {\n return resources.map((resource) => {\n if ('uri' in resource) {\n const url = new URL(resource.uri, `${scheme}://`);\n const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`;\n\n return {\n ...resource,\n uri,\n };\n }\n\n const url = new URL(resource.uriTemplate, `${scheme}://`);\n const uriTemplate = decodeURI(\n url.href\n ) as `${Scheme}://${typeof resource.uriTemplate}`;\n\n return {\n ...resource,\n uriTemplate,\n };\n });\n}\n\n/**\n * Helper function to create a JSON resource response.\n */\nexport function jsonResourceResponse<Uri extends string, Response>(\n uri: Uri,\n response: Response\n) {\n return {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(response),\n };\n}\n\n/**\n * Helper function to define an MCP tool while preserving type information.\n */\nexport function tool<\n Params extends z.ZodObject<any>,\n OutputSchema extends z.ZodObject<any>,\n>(tool: Tool<Params, OutputSchema>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n name: string;\n arguments: Record<string, unknown>;\n annotations?: Annotations;\n};\n\ntype ToolCallSuccessDetails = ToolCallBaseDetails & {\n success: true;\n data: unknown;\n};\n\ntype ToolCallErrorDetails = ToolCallBaseDetails & {\n success: false;\n error: unknown;\n};\n\nexport type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;\n\nexport type InitCallback = (initData: InitData) => void | Promise<void>;\nexport type ToolCallCallback = (details: ToolCallDetails) => void;\nexport type PropCallback<T> = () => T | Promise<T>;\nexport type Prop<T> = T | PropCallback<T>;\n\nexport type McpServerOptions = {\n /**\n * The name of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n name: string;\n\n /**\n * The title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Optional instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions?: string;\n\n /**\n * Callback for after a tool is called.\n */\n onToolCall?: ToolCallCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?:\n | Record<string, Tool>\n | ((\n ctx?: ServerContext\n ) => Record<string, Tool> | Promise<Record<string, Tool>>);\n\n /**\n * Multi-round-trip `requestState` integrity hook (protocol revision\n * 2026-07-28), passed straight through to the underlying SDK `Server`.\n *\n * Configure this with `createRequestStateCodec`'s `verify` to\n * authenticate `requestState` a tool mints via `inputRequired(...)`.\n * Leaving it unset keeps the SDK's passthrough behavior.\n */\n requestState?: {\n verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;\n };\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer(options: McpServerOptions) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n instructions: options.instructions,\n requestState: options.requestState,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools(ctx?: ServerContext) {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools(ctx)\n : options.tools;\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n 'resources/list',\n async (): Promise<ListResourcesResult> => {\n const allResources = await getResources();\n return {\n resources: allResources\n .filter((resource) => 'uri' in resource)\n .map(({ uri, name, description, mimeType }) => {\n return {\n uri,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n 'resources/templates/list',\n async (): Promise<ListResourceTemplatesResult> => {\n const allResources = await getResources();\n return {\n resourceTemplates: allResources\n .filter((resource) => 'uriTemplate' in resource)\n .map(({ uriTemplate, name, description, mimeType }) => {\n return {\n uriTemplate,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n 'resources/read',\n async (request): Promise<ReadResourceResult> => {\n try {\n const allResources = await getResources();\n const { uri } = request.params;\n\n const resources = allResources.filter(\n (resource) => 'uri' in resource\n );\n const resource = resources.find((resource) =>\n compareUris(resource.uri, uri)\n );\n\n if (resource) {\n const result = await resource.read(uri as `${string}://${string}`);\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n }\n\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceTemplateUris = resourceTemplates.map(\n ({ uriTemplate }) => assertValidUri(uriTemplate)\n );\n\n const templateMatch = matchUriTemplate(uri, resourceTemplateUris);\n\n if (!templateMatch) {\n throw new Error('resource not found');\n }\n\n const resourceTemplate = resourceTemplates.find(\n (r) => r.uriTemplate === templateMatch.uri\n );\n\n if (!resourceTemplate) {\n throw new Error('resource not found');\n }\n\n const result = await resourceTemplate.read(\n uri as `${string}://${string}`,\n templateMatch.params\n );\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n } catch (error) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } as any;\n }\n }\n );\n }\n\n if (options.tools) {\n server.setRequestHandler(\n 'tools/list',\n async (_request, ctx): Promise<ListToolsResult> => {\n const tools = await getTools(ctx);\n\n return {\n tools: await Promise.all(\n Object.entries(tools)\n .filter(([, tool]) => !tool.hidden)\n .map(async ([name, { description, annotations, parameters }]) => {\n const inputSchema = z.toJSONSchema(parameters, {\n target: 'draft-7',\n });\n\n return {\n name,\n description:\n typeof description === 'function'\n ? await description()\n : description,\n annotations,\n // Casting the same as the SDK does:\n // https://github.com/modelcontextprotocol/typescript-sdk/blob/fb07af810b51003c338dc4885a9e42f54519f9af/src/server/mcp.ts#L154\n inputSchema: inputSchema as McpTool['inputSchema'],\n };\n })\n ),\n } satisfies ListToolsResult;\n }\n );\n\n server.setRequestHandler('tools/call', async (request, ctx) => {\n try {\n const tools = await getTools(ctx);\n const toolName = request.params.name;\n\n if (!(toolName in tools)) {\n throw new Error('tool not found');\n }\n\n const tool = tools[toolName];\n\n if (!tool) {\n throw new Error('tool not found');\n }\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const executeWithCallback = async (tool: Tool) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args, ctx)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n try {\n options.onToolCall?.({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\n });\n } catch (error) {\n // Don't fail the tool call if the callback fails\n console.error('Failed to run tool callback', error);\n }\n\n // Unwrap result\n if (!res.success) {\n throw res.error;\n }\n return res.data;\n };\n\n const result = await executeWithCallback(tool);\n\n // An InputRequiredResult or a direct CallToolResult is already\n // shaped for the wire; pass it through instead of JSON-wrapping it.\n if (isInputRequiredResult(result) || isCallToolResult(result)) {\n return result;\n }\n\n const content =\n result != null\n ? [{ type: 'text' as const, text: JSON.stringify(result) }]\n : [];\n\n return {\n content,\n };\n } catch (error) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n };\n }\n });\n }\n\n return server;\n}\n\nfunction isInputRequiredResult(value: unknown): value is InputRequiredResult {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { resultType?: unknown }).resultType === 'input_required'\n );\n}\n\nfunction enumerateError(error: unknown) {\n if (!error) {\n return error;\n }\n\n if (typeof error !== 'object') {\n return error;\n }\n\n const newError: Record<string, unknown> = {};\n\n const errorProps = ['name', 'message'] as const;\n\n for (const prop of errorProps) {\n if (prop in error) {\n newError[prop] = (error as Record<string, unknown>)[prop];\n }\n }\n\n return newError;\n}\n","import type { ExtractParams } from './types.js';\n\n/**\n * Asserts that a URI is valid.\n */\nexport function assertValidUri(uri: string) {\n try {\n new URL(uri);\n return uri;\n } catch {\n throw new Error(`invalid uri: ${uri}`);\n }\n}\n\n/**\n * Compares two URIs.\n */\nexport function compareUris(uriA: string, uriB: string): boolean {\n const urlA = new URL(uriA);\n const urlB = new URL(uriB);\n\n return urlA.href === urlB.href;\n}\n\n/**\n * Matches a URI to a RFC 6570 URI Template (resourceUris) and extracts\n * the parameters.\n *\n * Currently only supports simple string parameters.\n */\nexport function matchUriTemplate<Templates extends string[]>(\n uri: string,\n uriTemplates: Templates\n):\n | {\n uri: Templates[number];\n params: { [Param in ExtractParams<Templates[number]>]: string };\n }\n | undefined {\n const url = new URL(uri);\n const segments = url.pathname.split('/').slice(1);\n\n for (const resourceUri of uriTemplates) {\n const resourceUrl = new URL(resourceUri);\n const resourceSegments = decodeURIComponent(resourceUrl.pathname)\n .split('/')\n .slice(1);\n\n if (segments.length !== resourceSegments.length) {\n continue;\n }\n\n const params: Record<string, string> = {};\n let isMatch = true;\n\n for (let i = 0; i < segments.length; i++) {\n const resourceSegment = resourceSegments[i];\n const segment = segments[i];\n\n if (!resourceSegment || !segment) {\n break;\n }\n\n if (resourceSegment.startsWith('{') && resourceSegment.endsWith('}')) {\n const paramKey = resourceSegment.slice(1, -1);\n\n if (!paramKey) {\n break;\n }\n\n params[paramKey] = segment;\n } else if (segments[i] !== resourceSegments[i]) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n return {\n uri: resourceUri,\n params: params as {\n [Param in ExtractParams<Templates[number]>]: string;\n },\n };\n }\n }\n}\n","import type { JSONRPCMessage, Transport } from '@modelcontextprotocol/server';\n\nimport type { DuplexStream } from './types.js';\n\n/**\n * An MCP transport built on top of a duplex stream.\n * It uses a `ReadableStream` to receive messages and a `WritableStream` to send messages.\n *\n * Useful if you wish to pipe messages over your own stream-based transport or directly between two streams.\n */\nexport class StreamTransport\n implements Transport, DuplexStream<JSONRPCMessage>\n{\n #readableStreamController?: ReadableStreamDefaultController<JSONRPCMessage>;\n #writeableStreamController?: WritableStreamDefaultController;\n\n ready: Promise<void>;\n\n readable: ReadableStream<JSONRPCMessage>;\n writable: WritableStream<JSONRPCMessage>;\n\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n\n constructor() {\n let resolveReadReady: () => void;\n let resolveWriteReady: () => void;\n\n const readReady = new Promise<void>((resolve) => {\n resolveReadReady = resolve;\n });\n\n const writeReady = new Promise<void>((resolve) => {\n resolveWriteReady = resolve;\n });\n\n this.ready = Promise.all([readReady, writeReady]).then(() => {});\n\n this.readable = new ReadableStream({\n start: (controller) => {\n this.#readableStreamController = controller;\n resolveReadReady();\n },\n });\n\n this.writable = new WritableStream({\n start: (controller) => {\n this.#writeableStreamController = controller;\n resolveWriteReady();\n },\n write: (message) => {\n this.onmessage?.(message);\n },\n });\n }\n\n async start() {\n await this.ready;\n }\n\n async send(message: JSONRPCMessage) {\n if (!this.#readableStreamController) {\n throw new Error('readable stream not initialized');\n }\n this.#readableStreamController.enqueue(message);\n }\n\n async close() {\n this.#readableStreamController?.error(new Error('connection closed'));\n this.#writeableStreamController?.error(new Error('connection closed'));\n this.onclose?.();\n }\n}\n"],"mappings":"AAAA,OAAS,oBAAAA,EAAkB,UAAAC,MAAc,+BAczC,OAAS,KAAAC,MAAS,SCTX,SAASC,EAAeC,EAAa,CAC1C,GAAI,CACF,WAAI,IAAIA,CAAG,EACJA,CACT,MAAQ,CACN,MAAM,IAAI,MAAM,gBAAgBA,CAAG,EAAE,CACvC,CACF,CAKO,SAASC,EAAYC,EAAcC,EAAuB,CAC/D,IAAMC,EAAO,IAAI,IAAIF,CAA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jB,IACVe,EAASE,CAAI,EAAKjB,EAAkCiB,CAAI,GAI5D,OAAOF,CACT,CEvlBO,IAAMG,EAAN,KAEP,CACEC,GACAC,GAEA,MAEA,SACA,SAEA,QACA,QACA,UAEA,aAAc,CACZ,IAAIC,EACAC,EAEEC,EAAY,IAAI,QAAeC,GAAY,CAC/CH,EAAmBG,CACrB,CAAC,EAEKC,EAAa,IAAI,QAAeD,GAAY,CAChDF,EAAoBE,CACtB,CAAC,EAED,KAAK,MAAQ,QAAQ,IAAI,CAACD,EAAWE,CAAU,CAAC,EAAE,KAAK,IAAM,CAAC,CAAC,EAE/D,KAAK,SAAW,IAAI,eAAe,CACjC,MAAQC,GAAe,CACrB,KAAKP,GAA4BO,EACjCL,EAAiB,CACnB,CACF,CAAC,EAED,KAAK,SAAW,IAAI,eAAe,CACjC,MAAQK,GAAe,CACrB,KAAKN,GAA6BM,EAClCJ,EAAkB,CACpB,EACA,MAAQK,GAAY,CAClB,KAAK,YAAYA,CAAO,CAC1B,CACF,CAAC,CACH,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,KACb,CAEA,MAAM,KAAKA,EAAyB,CAClC,GAAI,CAAC,KAAKR,GACR,MAAM,IAAI,MAAM,iCAAiC,EAEnD,KAAKA,GAA0B,QAAQQ,CAAO,CAChD,CAEA,MAAM,OAAQ,CACZ,KAAKR,IAA2B,MAAM,IAAI,MAAM,mBAAmB,CAAC,EACpE,KAAKC,IAA4B,MAAM,IAAI,MAAM,mBAAmB,CAAC,EACrE,KAAK,UAAU,CACjB,CACF","names":["isCallToolResult","Server","z","assertValidUri","uri","compareUris","uriA","uriB","urlA","urlB","matchUriTemplate","uriTemplates","segments","resourceUri","resourceUrl","resourceSegments","params","isMatch","i","resourceSegment","segment","paramKey","resource","uri","resourceTemplate","uriTemplate","jsonResource","jsonResourceTemplate","resources","scheme","url","jsonResourceResponse","response","tool","createMcpServer","options","capabilities","server","Server","getResources","getTools","ctx","clientInfo","clientCapabilities","initData","name","description","mimeType","request","allResources","compareUris","result","resourceTemplates","resourceTemplateUris","assertValidUri","templateMatch","matchUriTemplate","r","error","enumerateError","_request","tools","annotations","parameters","inputSchema","z","toolName","args","res","data","isInputRequiredResult","isCallToolResult","value","newError","errorProps","prop","StreamTransport","#readableStreamController","#writeableStreamController","resolveReadReady","resolveWriteReady","readReady","resolve","writeReady","controller","message"]}
|