@supabase/mcp-utils 0.8.0 → 0.10.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 +67 -7
- package/dist/index.d.ts +67 -7
- 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
|
|
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 g=Symbol.for("supabase.mcp.callerError"),T= exports.ToolCallerError =class extends Error{constructor(t,r){super(t,r),this.name="ToolCallerError",this[g]=!0,_optionalChain([r, 'optionalAccess', _ => _.kind])!==void 0&&(this.kind=r.kind)}};function F(e){return typeof e=="object"&&e!==null&&g in e&&e[g]===!0}var _server = require('@modelcontextprotocol/server');var _v4 = require('zod/v4');function C(e){try{return new URL(e),e}catch (e2){throw new Error(`invalid uri: ${e}`)}}function S(e,t){let r=new URL(e),o=new URL(t);return r.href===o.href}function P(e,t){let o=new URL(e).pathname.split("/").slice(1);for(let m of t){let l=new URL(m),n=decodeURIComponent(l.pathname).split("/").slice(1);if(o.length!==n.length)continue;let s={},i=!0;for(let c=0;c<o.length;c++){let a=n[c],d=o[c];if(!a||!d)break;if(a.startsWith("{")&&a.endsWith("}")){let f=a.slice(1,-1);if(!f)break;s[f]=d}else if(o[c]!==n[c]){i=!1;break}}if(i)return{uri:m,params:s}}}function O(e,t){if(!e)return;let r=performance.now(),o;try{if(o=e(t),o&&"then"in o&&typeof o.then=="function"){Promise.resolve(o).catch(()=>{});return}}catch (e3){return}if(!o)return;let m=!1,l="completed";return{tool:{record(n){m||E(()=>o.record(n))},setOutcome(n){m||(l=n)}},end(n){if(m)return;m=!0;let s=performance.now()-r;E(()=>o.end({result:n,durationMs:s}))},outcome:()=>l}}function E(e){try{Promise.resolve(e()).catch(()=>{})}catch (e4){}}function W(e,t){return{uri:e,...t}}function H(e,t){return{uriTemplate:e,...t}}function K(e,t){return{uri:e,mimeType:"application/json",...t}}function V(e,t){return{uriTemplate:e,mimeType:"application/json",...t}}function G(e,t){return t.map(r=>{if("uri"in r){let l=new URL(r.uri,`${e}://`),n=decodeURI(l.href);return{...r,uri:n}}let o=new URL(r.uriTemplate,`${e}://`),m=decodeURI(o.href);return{...r,uriTemplate:m}})}function Q(e,t){return{uri:e,mimeType:"application/json",text:JSON.stringify(t)}}function X(e){return e}function Y(e){let t={};e.resources&&(t.resources={}),e.tools&&(t.tools={});let r=new (0, _server.Server)({name:e.name,title:e.title,version:e.version},{capabilities:t,instructions:e.instructions,requestState:e.requestState});async function o(){if(!e.resources)throw new Error("resources not available");return typeof e.resources=="function"?await e.resources():e.resources}async function m(n){if(!e.tools)throw new Error("tools not available");return typeof e.tools=="function"?await e.tools(n):e.tools}async function l(n,s){let i=O(e.observer,{method:n}),c="handler_error";try{let a=await s();return c="isError"in a&&a.isError===!0?"tool_error":"completed",a}finally{_optionalChain([i, 'optionalAccess', _2 => _2.end, 'call', _3 => _3(c)])}}return r.oninitialized=async()=>{let n=r.getClientVersion(),s=r.getClientCapabilities();if(!n)throw new Error("client info not available after initialization");if(!s)throw new Error("client capabilities not available after initialization");let i={clientInfo:n,clientCapabilities:s};await _optionalChain([e, 'access', _4 => _4.onInitialize, 'optionalCall', _5 => _5(i)])},e.resources&&(r.setRequestHandler("resources/list",()=>l("resources/list",async()=>({resources:(await o()).filter(s=>"uri"in s).map(({uri:s,name:i,description:c,mimeType:a})=>({uri:s,name:i,description:c,mimeType:a}))}))),r.setRequestHandler("resources/templates/list",()=>l("resources/templates/list",async()=>({resourceTemplates:(await o()).filter(s=>"uriTemplate"in s).map(({uriTemplate:s,name:i,description:c,mimeType:a})=>({uriTemplate:s,name:i,description:c,mimeType:a}))}))),r.setRequestHandler("resources/read",n=>l("resources/read",async()=>{try{let s=await o(),{uri:i}=n.params,a=s.filter(u=>"uri"in u).find(u=>S(u.uri,i));if(a){let u=await a.read(i);return{contents:Array.isArray(u)?u:[u]}}let d=s.filter(u=>"uriTemplate"in u),f=d.map(({uriTemplate:u})=>C(u)),p=P(i,f);if(!p)throw new Error("resource not found");let R=d.find(u=>u.uriTemplate===p.uri);if(!R)throw new Error("resource not found");let y=await R.read(i,p.params);return{contents:Array.isArray(y)?y:[y]}}catch(s){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:k(s)})}]}}}))),e.tools&&(r.setRequestHandler("tools/list",(n,s)=>l("tools/list",async()=>{let i=await m(s);return{tools:await Promise.all(Object.entries(i).filter(([,c])=>!c.hidden).map(async([c,{description:a,annotations:d,parameters:f}])=>{let p=_v4.z.toJSONSchema(f,{target:"draft-7"});return{name:c,description:typeof a=="function"?await a():a,annotations:d,inputSchema:p}}))}})),r.setRequestHandler("tools/call",async(n,s)=>{let i=n.params.name,c="other";if(e.observer)try{c=_nullishCoalesce(_optionalChain([e, 'access', _6 => _6.classifyTool, 'optionalCall', _7 => _7(i)]), () => ("other"))}catch (e5){}let a=O(e.observer,{method:"tools/call",tool:c}),d="handler_error",f=p=>{try{_optionalChain([e, 'access', _8 => _8.onToolCall, 'optionalCall', _9 => _9(p)])}catch(R){console.error("Failed to run tool callback",R)}};try{let p=await m(s),R=_nullishCoalesce(n.params.arguments, () => ({})),y=p[i];if(!y)throw f({name:i,arguments:R,success:!1,error:new T("tool not found")}),new Error("tool not found");let v=y.parameters.strict().safeParse(R);if(!v.success)throw f({name:i,arguments:R,annotations:y.annotations,success:!1,error:new T(v.error.message,{cause:v.error})}),v.error;let u=v.data,b=await(async w=>{let x=await w.execute(u,s,_optionalChain([a, 'optionalAccess', _10 => _10.tool])).then(h=>({success:!0,data:h})).catch(h=>({success:!1,error:h}));if(f({name:i,arguments:u,annotations:w.annotations,...x}),!x.success)throw x.error;return x.data})(y);if(D(b))return d="input_required",b;if(_server.isCallToolResult.call(void 0, b))return d=b.isError?"tool_error":_nullishCoalesce(_optionalChain([a, 'optionalAccess', _11 => _11.outcome, 'call', _12 => _12()]), () => ("completed")),b;let q=b!=null?[{type:"text",text:JSON.stringify(b)}]:[];return d=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _13 => _13.outcome, 'call', _14 => _14()]), () => ("completed")),{content:q}}catch(p){let R={isError:!0,content:[{type:"text",text:JSON.stringify({error:k(p)})}]};return d="tool_error",R}finally{_optionalChain([a, 'optionalAccess', _15 => _15.end, 'call', _16 => _16(d)])}})),r}function D(e){return typeof e=="object"&&e!==null&&e.resultType==="input_required"}function k(e){if(!e||typeof e!="object")return e;let t={},r=["name","message"];for(let o of r)o in e&&(t[o]=e[o]);return t}var U=class{#e;#t;constructor(){let t,r,o=new Promise(l=>{t=l}),m=new Promise(l=>{r=l});this.ready=Promise.all([o,m]).then(()=>{}),this.readable=new ReadableStream({start:l=>{this.#e=l,t()}}),this.writable=new WritableStream({start:l=>{this.#t=l,r()},write:l=>{_optionalChain([this, 'access', _17 => _17.onmessage, 'optionalCall', _18 => _18(l)])}})}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', _19 => _19.#e, 'optionalAccess', _20 => _20.error, 'call', _21 => _21(new Error("connection closed"))]),_optionalChain([this, 'access', _22 => _22.#t, 'optionalAccess', _23 => _23.error, 'call', _24 => _24(new Error("connection closed"))]),_optionalChain([this, 'access', _25 => _25.onclose, 'optionalCall', _26 => _26()])}};exports.StreamTransport = U; exports.ToolCallerError = T; exports.createMcpServer = Y; exports.isToolCallerError = F; exports.jsonResource = K; exports.jsonResourceResponse = Q; exports.jsonResourceTemplate = V; exports.resource = W; exports.resourceTemplate = H; exports.resources = G; exports.tool = X;
|
|
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,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"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/server.ts","../src/util.ts"],"names":["toolCallerErrorBrand","ToolCallerError","message","options","isToolCallerError","error","assertValidUri","uri"],"mappings":"AAAA,qrBAAMA,CAAAA,CAAuB,MAAA,CAAO,GAAA,CAAI,0BAA0B,CAAA,CAcrDC,CAAAA,2BAAN,MAAA,QAA8B,KAAM,CAIzC,WAAA,CACEC,CAAAA,CACAC,CAAAA,CACA,CACA,KAAA,CAAMD,CAAAA,CAASC,CAAO,CAAA,CACtB,IAAA,CAAK,IAAA,CAAO,iBAAA,CAEZ,IAAA,CAAKH,CAAoB,CAAA,CAAI,CAAA,CAAA,iBACzBG,CAAAA,2BAAS,MAAA,GAAS,KAAA,CAAA,EAAA,CACpB,IAAA,CAAK,IAAA,CAAOA,CAAAA,CAAQ,IAAA,CAExB,CACF,CAAA,CAKO,SAASC,CAAAA,CAAkBC,CAAAA,CAA0C,CAC1E,OACE,OAAOA,CAAAA,EAAU,QAAA,EACjBA,CAAAA,GAAU,IAAA,EACVL,EAAAA,GAAwBK,CAAAA,EACxBA,CAAAA,CAAML,CAAoB,CAAA,GAAM,CAAA,CAEpC,CC1CA,sDAAyC,4BAcvB,SCTFM,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":["const toolCallerErrorBrand = Symbol.for('supabase.mcp.callerError');\n\n/**\n * What a caller error asks of the caller. `confirmation_required` means the\n * tool needs a confirmation step first: a mismatched `confirm_cost_id`, or a\n * missing one when inline cost confirmation is configured. Without it, the\n * schema check rejects a missing `confirm_cost_id` first, and the error has a\n * `ZodError` cause and no kind.\n */\nexport type ToolCallerErrorKind = 'confirmation_required';\n\n/**\n * A tool error caused by the caller's input, comparable to an HTTP 4xx.\n */\nexport class ToolCallerError extends Error {\n declare [toolCallerErrorBrand]: true;\n declare readonly kind?: ToolCallerErrorKind;\n\n constructor(\n message: string,\n options?: ErrorOptions & { kind?: ToolCallerErrorKind }\n ) {\n super(message, options);\n this.name = 'ToolCallerError';\n // Assigned here because a class field initializer miscompiles in the CJS build.\n this[toolCallerErrorBrand] = true;\n if (options?.kind !== undefined) {\n this.kind = options.kind;\n }\n }\n}\n\n/**\n * Checks the global symbol brand so errors from another installed copy of this package still match.\n */\nexport function isToolCallerError(error: unknown): error is ToolCallerError {\n return (\n typeof error === 'object' &&\n error !== null &&\n toolCallerErrorBrand in error &&\n error[toolCallerErrorBrand] === true\n );\n}\n","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 { ToolCallerError } from './errors.js';\nimport type { ExtractParams } from './types.js';\nimport { assertValidUri, compareUris, matchUriTemplate } from './util.js';\nimport { beginObservation } from './observation.js';\nimport type {\n ObservationEnd,\n ObservedMethod,\n ToolObservation,\n RequestObserver,\n} from './observation.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 Fact = never,\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 * The optional observation handle records custom facts and sets an explicit\n * outcome. Its methods isolate sink failures and become inert after settlement.\n */\n execute: (\n params: z.infer<Params>,\n ctx: ServerContext,\n observation?: ToolObservation<Fact>\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 Fact = never,\n>(tool: Tool<Params, OutputSchema, Fact>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n /**\n * The tool name the client sent. It may not be a registered tool, so it is\n * an unbounded, client-chosen value: don't use it as a metric label as-is.\n */\n name: string;\n arguments: Record<string, unknown>;\n /** Absent for unknown tools. */\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<Bucket extends string = never, Fact = never> = {\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<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n | ((\n ctx?: ServerContext\n ) =>\n | Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n | Promise<\n Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n >);\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 /** Optional per-request observer; see ObservedMethod for covered handlers. */\n observer?: RequestObserver<Bucket, Fact>;\n classifyTool?: (name: string) => Bucket | 'other';\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<Bucket extends string = never, Fact = never>(\n options: McpServerOptions<Bucket, Fact>\n) {\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 async function observed<Result extends object>(\n method: Exclude<ObservedMethod, 'tools/call'>,\n run: () => Promise<Result>\n ): Promise<Result> {\n const scope = beginObservation(options.observer, { method });\n let outcome: ObservationEnd['result'] = 'handler_error';\n try {\n const result = await run();\n outcome =\n 'isError' in result && result.isError === true\n ? 'tool_error'\n : 'completed';\n return result;\n } finally {\n scope?.end(outcome);\n }\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 (): Promise<ListResourcesResult> =>\n observed('resources/list', async () => {\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 (): Promise<ListResourceTemplatesResult> =>\n observed('resources/templates/list', async () => {\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 (request): Promise<ReadResourceResult> =>\n observed('resources/read', async () => {\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(\n uri as `${string}://${string}`\n );\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 // Preserve the existing resource error payload despite the SDK result type.\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } as unknown as ReadResourceResult;\n }\n })\n );\n }\n\n if (options.tools) {\n server.setRequestHandler(\n 'tools/list',\n (_request, ctx): Promise<ListToolsResult> =>\n observed('tools/list', async () => {\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(\n 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 ),\n } satisfies ListToolsResult;\n })\n );\n\n server.setRequestHandler('tools/call', async (request, ctx) => {\n const toolName = request.params.name;\n let tool: Bucket | 'other' = 'other';\n if (options.observer) {\n try {\n tool = options.classifyTool?.(toolName) ?? 'other';\n } catch {}\n }\n const scope = beginObservation(options.observer, {\n method: 'tools/call',\n tool,\n });\n let outcome: ObservationEnd['result'] = 'handler_error';\n\n const reportToolCall = (details: ToolCallDetails) => {\n try {\n options.onToolCall?.(details);\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\n try {\n const tools = await getTools(ctx);\n const rawArgs = request.params.arguments ?? {};\n const tool = tools[toolName];\n\n // The client still sees the original error; the hook gets a caller error.\n if (!tool) {\n reportToolCall({\n name: toolName,\n arguments: rawArgs,\n success: false,\n error: new ToolCallerError('tool not found'),\n });\n throw new Error('tool not found');\n }\n\n const parsed = tool.parameters.strict().safeParse(rawArgs);\n if (!parsed.success) {\n reportToolCall({\n name: toolName,\n arguments: rawArgs,\n annotations: tool.annotations,\n success: false,\n error: new ToolCallerError(parsed.error.message, {\n cause: parsed.error,\n }),\n });\n throw parsed.error;\n }\n const args = parsed.data;\n\n const executeWithCallback = async (\n tool: Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>\n ) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args, ctx, scope?.tool)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n reportToolCall({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\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 is already shaped for the wire.\n if (isInputRequiredResult(result)) {\n outcome = 'input_required';\n return result;\n }\n\n // A direct CallToolResult is already shaped for the wire; pass it\n // through instead of JSON-wrapping it.\n if (isCallToolResult(result)) {\n outcome = result.isError\n ? 'tool_error'\n : (scope?.outcome() ?? 'completed');\n return result;\n }\n\n const content =\n result != null\n ? [{ type: 'text' as const, text: JSON.stringify(result) }]\n : [];\n\n outcome = scope?.outcome() ?? 'completed';\n return {\n content,\n };\n } catch (error) {\n const result = {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } satisfies CallToolResult;\n outcome = 'tool_error';\n return result;\n } finally {\n scope?.end(outcome);\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,6 +1,30 @@
|
|
|
1
1
|
import { ListToolsResult, ServerContext, InputRequiredResult, CallToolResult, Implementation, ClientCapabilities, Server, Transport, JSONRPCMessage } from '@modelcontextprotocol/server';
|
|
2
2
|
import { z } from 'zod/v4';
|
|
3
3
|
|
|
4
|
+
declare const toolCallerErrorBrand: unique symbol;
|
|
5
|
+
/**
|
|
6
|
+
* What a caller error asks of the caller. `confirmation_required` means the
|
|
7
|
+
* tool needs a confirmation step first: a mismatched `confirm_cost_id`, or a
|
|
8
|
+
* missing one when inline cost confirmation is configured. Without it, the
|
|
9
|
+
* schema check rejects a missing `confirm_cost_id` first, and the error has a
|
|
10
|
+
* `ZodError` cause and no kind.
|
|
11
|
+
*/
|
|
12
|
+
type ToolCallerErrorKind = 'confirmation_required';
|
|
13
|
+
/**
|
|
14
|
+
* A tool error caused by the caller's input, comparable to an HTTP 4xx.
|
|
15
|
+
*/
|
|
16
|
+
declare class ToolCallerError extends Error {
|
|
17
|
+
[toolCallerErrorBrand]: true;
|
|
18
|
+
readonly kind?: ToolCallerErrorKind;
|
|
19
|
+
constructor(message: string, options?: ErrorOptions & {
|
|
20
|
+
kind?: ToolCallerErrorKind;
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Checks the global symbol brand so errors from another installed copy of this package still match.
|
|
25
|
+
*/
|
|
26
|
+
declare function isToolCallerError(error: unknown): error is ToolCallerError;
|
|
27
|
+
|
|
4
28
|
/**
|
|
5
29
|
* A web stream that can be both read from and written to.
|
|
6
30
|
*/
|
|
@@ -17,6 +41,31 @@ interface DuplexStream<T> {
|
|
|
17
41
|
*/
|
|
18
42
|
type ExtractParams<Path extends string> = Path extends `${string}{${infer P}}${infer Rest}` ? P | ExtractParams<Rest> : never;
|
|
19
43
|
|
|
44
|
+
/** Observations describe handler attempts, not transport delivery or backend commit. */
|
|
45
|
+
type ObservedMethod = 'tools/call' | 'tools/list' | 'resources/list' | 'resources/templates/list' | 'resources/read';
|
|
46
|
+
type ObservationContext<Bucket extends string = never> = Readonly<{
|
|
47
|
+
method: 'tools/call';
|
|
48
|
+
tool: Bucket | 'other';
|
|
49
|
+
}> | Readonly<{
|
|
50
|
+
method: Exclude<ObservedMethod, 'tools/call'>;
|
|
51
|
+
}>;
|
|
52
|
+
type ToolOutcome = 'completed' | 'declined' | 'cancelled';
|
|
53
|
+
type ToolObservation<Fact = never> = Readonly<{
|
|
54
|
+
record: (fact: Fact) => void;
|
|
55
|
+
setOutcome: (result: ToolOutcome) => void;
|
|
56
|
+
}>;
|
|
57
|
+
type ObservationEnd = Readonly<{
|
|
58
|
+
result: ToolOutcome | 'input_required' | 'tool_error' | 'handler_error';
|
|
59
|
+
durationMs: number;
|
|
60
|
+
}>;
|
|
61
|
+
/** Sink failures are isolated; custom facts remain the producer's responsibility. */
|
|
62
|
+
type RequestObservation<Fact = never> = Readonly<{
|
|
63
|
+
record: (fact: Fact) => void | Promise<void>;
|
|
64
|
+
end: (result: ObservationEnd) => void | Promise<void>;
|
|
65
|
+
}>;
|
|
66
|
+
/** Synchronous factory; promises and thenables are unsupported. */
|
|
67
|
+
type RequestObserver<Bucket extends string = never, Fact = never> = (context: ObservationContext<Bucket>) => RequestObservation<Fact> | undefined;
|
|
68
|
+
|
|
20
69
|
type Scheme = string;
|
|
21
70
|
type Annotations = NonNullable<ListToolsResult['tools'][number]['annotations']>;
|
|
22
71
|
type Resource<Uri extends string = string, Result = unknown> = {
|
|
@@ -35,7 +84,7 @@ type ResourceTemplate<Uri extends string = string, Result = unknown> = {
|
|
|
35
84
|
[Param in ExtractParams<Uri>]: string;
|
|
36
85
|
}): Promise<Result>;
|
|
37
86
|
};
|
|
38
|
-
type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema extends z.ZodObject<any> = z.ZodObject<any
|
|
87
|
+
type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema extends z.ZodObject<any> = z.ZodObject<any>, Fact = never> = {
|
|
39
88
|
description: Prop<string>;
|
|
40
89
|
annotations?: Annotations;
|
|
41
90
|
parameters: Params;
|
|
@@ -51,8 +100,11 @@ type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema exten
|
|
|
51
100
|
* passed straight to the client instead of being JSON-wrapped; any other
|
|
52
101
|
* value is wrapped as today (`{ content: [{ type: 'text', text:
|
|
53
102
|
* JSON.stringify(value) }] }`).
|
|
103
|
+
*
|
|
104
|
+
* The optional observation handle records custom facts and sets an explicit
|
|
105
|
+
* outcome. Its methods isolate sink failures and become inert after settlement.
|
|
54
106
|
*/
|
|
55
|
-
execute(params: z.infer<Params>, ctx: ServerContext)
|
|
107
|
+
execute: (params: z.infer<Params>, ctx: ServerContext, observation?: ToolObservation<Fact>) => Promise<z.infer<OutputSchema> | InputRequiredResult | CallToolResult>;
|
|
56
108
|
};
|
|
57
109
|
/**
|
|
58
110
|
* Helper function to define an MCP resource while preserving type information.
|
|
@@ -85,14 +137,19 @@ declare function jsonResourceResponse<Uri extends string, Response>(uri: Uri, re
|
|
|
85
137
|
/**
|
|
86
138
|
* Helper function to define an MCP tool while preserving type information.
|
|
87
139
|
*/
|
|
88
|
-
declare function tool<Params extends z.ZodObject<any>, OutputSchema extends z.ZodObject<any
|
|
140
|
+
declare function tool<Params extends z.ZodObject<any>, OutputSchema extends z.ZodObject<any>, Fact = never>(tool: Tool<Params, OutputSchema, Fact>): Tool<Params, OutputSchema, Fact>;
|
|
89
141
|
type InitData = {
|
|
90
142
|
clientInfo: Implementation;
|
|
91
143
|
clientCapabilities: ClientCapabilities;
|
|
92
144
|
};
|
|
93
145
|
type ToolCallBaseDetails = {
|
|
146
|
+
/**
|
|
147
|
+
* The tool name the client sent. It may not be a registered tool, so it is
|
|
148
|
+
* an unbounded, client-chosen value: don't use it as a metric label as-is.
|
|
149
|
+
*/
|
|
94
150
|
name: string;
|
|
95
151
|
arguments: Record<string, unknown>;
|
|
152
|
+
/** Absent for unknown tools. */
|
|
96
153
|
annotations?: Annotations;
|
|
97
154
|
};
|
|
98
155
|
type ToolCallSuccessDetails = ToolCallBaseDetails & {
|
|
@@ -108,7 +165,7 @@ type InitCallback = (initData: InitData) => void | Promise<void>;
|
|
|
108
165
|
type ToolCallCallback = (details: ToolCallDetails) => void;
|
|
109
166
|
type PropCallback<T> = () => T | Promise<T>;
|
|
110
167
|
type Prop<T> = T | PropCallback<T>;
|
|
111
|
-
type McpServerOptions = {
|
|
168
|
+
type McpServerOptions<Bucket extends string = never, Fact = never> = {
|
|
112
169
|
/**
|
|
113
170
|
* The name of the MCP server. This will be sent to the client as part of
|
|
114
171
|
* the initialization process.
|
|
@@ -161,7 +218,7 @@ type McpServerOptions = {
|
|
|
161
218
|
* asks for the list of tools or invokes a tool. This allows for dynamic tools
|
|
162
219
|
* that can change after the server has started.
|
|
163
220
|
*/
|
|
164
|
-
tools?: Record<string, Tool
|
|
221
|
+
tools?: Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>> | ((ctx?: ServerContext) => Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>> | Promise<Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>>);
|
|
165
222
|
/**
|
|
166
223
|
* Multi-round-trip `requestState` integrity hook (protocol revision
|
|
167
224
|
* 2026-07-28), passed straight through to the underlying SDK `Server`.
|
|
@@ -173,6 +230,9 @@ type McpServerOptions = {
|
|
|
173
230
|
requestState?: {
|
|
174
231
|
verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;
|
|
175
232
|
};
|
|
233
|
+
/** Optional per-request observer; see ObservedMethod for covered handlers. */
|
|
234
|
+
observer?: RequestObserver<Bucket, Fact>;
|
|
235
|
+
classifyTool?: (name: string) => Bucket | 'other';
|
|
176
236
|
};
|
|
177
237
|
/**
|
|
178
238
|
* Creates an MCP server with the given options.
|
|
@@ -180,7 +240,7 @@ type McpServerOptions = {
|
|
|
180
240
|
* Simplifies the process of creating an MCP server by providing a high-level
|
|
181
241
|
* API for defining resources and tools.
|
|
182
242
|
*/
|
|
183
|
-
declare function createMcpServer(options: McpServerOptions): Server;
|
|
243
|
+
declare function createMcpServer<Bucket extends string = never, Fact = never>(options: McpServerOptions<Bucket, Fact>): Server;
|
|
184
244
|
|
|
185
245
|
/**
|
|
186
246
|
* An MCP transport built on top of a duplex stream.
|
|
@@ -202,4 +262,4 @@ declare class StreamTransport implements Transport, DuplexStream<JSONRPCMessage>
|
|
|
202
262
|
close(): Promise<void>;
|
|
203
263
|
}
|
|
204
264
|
|
|
205
|
-
export { type Annotations, type DuplexStream, type ExtractParams, type InitCallback, type InitData, type McpServerOptions, type Prop, type PropCallback, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, type ToolCallCallback, type ToolCallDetails, createMcpServer, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
|
|
265
|
+
export { type Annotations, type DuplexStream, type ExtractParams, type InitCallback, type InitData, type McpServerOptions, type ObservationContext, type ObservationEnd, type ObservedMethod, type Prop, type PropCallback, type RequestObservation, type RequestObserver, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, type ToolCallCallback, type ToolCallDetails, ToolCallerError, type ToolCallerErrorKind, type ToolObservation, type ToolOutcome, createMcpServer, isToolCallerError, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
import { ListToolsResult, ServerContext, InputRequiredResult, CallToolResult, Implementation, ClientCapabilities, Server, Transport, JSONRPCMessage } from '@modelcontextprotocol/server';
|
|
2
2
|
import { z } from 'zod/v4';
|
|
3
3
|
|
|
4
|
+
declare const toolCallerErrorBrand: unique symbol;
|
|
5
|
+
/**
|
|
6
|
+
* What a caller error asks of the caller. `confirmation_required` means the
|
|
7
|
+
* tool needs a confirmation step first: a mismatched `confirm_cost_id`, or a
|
|
8
|
+
* missing one when inline cost confirmation is configured. Without it, the
|
|
9
|
+
* schema check rejects a missing `confirm_cost_id` first, and the error has a
|
|
10
|
+
* `ZodError` cause and no kind.
|
|
11
|
+
*/
|
|
12
|
+
type ToolCallerErrorKind = 'confirmation_required';
|
|
13
|
+
/**
|
|
14
|
+
* A tool error caused by the caller's input, comparable to an HTTP 4xx.
|
|
15
|
+
*/
|
|
16
|
+
declare class ToolCallerError extends Error {
|
|
17
|
+
[toolCallerErrorBrand]: true;
|
|
18
|
+
readonly kind?: ToolCallerErrorKind;
|
|
19
|
+
constructor(message: string, options?: ErrorOptions & {
|
|
20
|
+
kind?: ToolCallerErrorKind;
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Checks the global symbol brand so errors from another installed copy of this package still match.
|
|
25
|
+
*/
|
|
26
|
+
declare function isToolCallerError(error: unknown): error is ToolCallerError;
|
|
27
|
+
|
|
4
28
|
/**
|
|
5
29
|
* A web stream that can be both read from and written to.
|
|
6
30
|
*/
|
|
@@ -17,6 +41,31 @@ interface DuplexStream<T> {
|
|
|
17
41
|
*/
|
|
18
42
|
type ExtractParams<Path extends string> = Path extends `${string}{${infer P}}${infer Rest}` ? P | ExtractParams<Rest> : never;
|
|
19
43
|
|
|
44
|
+
/** Observations describe handler attempts, not transport delivery or backend commit. */
|
|
45
|
+
type ObservedMethod = 'tools/call' | 'tools/list' | 'resources/list' | 'resources/templates/list' | 'resources/read';
|
|
46
|
+
type ObservationContext<Bucket extends string = never> = Readonly<{
|
|
47
|
+
method: 'tools/call';
|
|
48
|
+
tool: Bucket | 'other';
|
|
49
|
+
}> | Readonly<{
|
|
50
|
+
method: Exclude<ObservedMethod, 'tools/call'>;
|
|
51
|
+
}>;
|
|
52
|
+
type ToolOutcome = 'completed' | 'declined' | 'cancelled';
|
|
53
|
+
type ToolObservation<Fact = never> = Readonly<{
|
|
54
|
+
record: (fact: Fact) => void;
|
|
55
|
+
setOutcome: (result: ToolOutcome) => void;
|
|
56
|
+
}>;
|
|
57
|
+
type ObservationEnd = Readonly<{
|
|
58
|
+
result: ToolOutcome | 'input_required' | 'tool_error' | 'handler_error';
|
|
59
|
+
durationMs: number;
|
|
60
|
+
}>;
|
|
61
|
+
/** Sink failures are isolated; custom facts remain the producer's responsibility. */
|
|
62
|
+
type RequestObservation<Fact = never> = Readonly<{
|
|
63
|
+
record: (fact: Fact) => void | Promise<void>;
|
|
64
|
+
end: (result: ObservationEnd) => void | Promise<void>;
|
|
65
|
+
}>;
|
|
66
|
+
/** Synchronous factory; promises and thenables are unsupported. */
|
|
67
|
+
type RequestObserver<Bucket extends string = never, Fact = never> = (context: ObservationContext<Bucket>) => RequestObservation<Fact> | undefined;
|
|
68
|
+
|
|
20
69
|
type Scheme = string;
|
|
21
70
|
type Annotations = NonNullable<ListToolsResult['tools'][number]['annotations']>;
|
|
22
71
|
type Resource<Uri extends string = string, Result = unknown> = {
|
|
@@ -35,7 +84,7 @@ type ResourceTemplate<Uri extends string = string, Result = unknown> = {
|
|
|
35
84
|
[Param in ExtractParams<Uri>]: string;
|
|
36
85
|
}): Promise<Result>;
|
|
37
86
|
};
|
|
38
|
-
type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema extends z.ZodObject<any> = z.ZodObject<any
|
|
87
|
+
type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema extends z.ZodObject<any> = z.ZodObject<any>, Fact = never> = {
|
|
39
88
|
description: Prop<string>;
|
|
40
89
|
annotations?: Annotations;
|
|
41
90
|
parameters: Params;
|
|
@@ -51,8 +100,11 @@ type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema exten
|
|
|
51
100
|
* passed straight to the client instead of being JSON-wrapped; any other
|
|
52
101
|
* value is wrapped as today (`{ content: [{ type: 'text', text:
|
|
53
102
|
* JSON.stringify(value) }] }`).
|
|
103
|
+
*
|
|
104
|
+
* The optional observation handle records custom facts and sets an explicit
|
|
105
|
+
* outcome. Its methods isolate sink failures and become inert after settlement.
|
|
54
106
|
*/
|
|
55
|
-
execute(params: z.infer<Params>, ctx: ServerContext)
|
|
107
|
+
execute: (params: z.infer<Params>, ctx: ServerContext, observation?: ToolObservation<Fact>) => Promise<z.infer<OutputSchema> | InputRequiredResult | CallToolResult>;
|
|
56
108
|
};
|
|
57
109
|
/**
|
|
58
110
|
* Helper function to define an MCP resource while preserving type information.
|
|
@@ -85,14 +137,19 @@ declare function jsonResourceResponse<Uri extends string, Response>(uri: Uri, re
|
|
|
85
137
|
/**
|
|
86
138
|
* Helper function to define an MCP tool while preserving type information.
|
|
87
139
|
*/
|
|
88
|
-
declare function tool<Params extends z.ZodObject<any>, OutputSchema extends z.ZodObject<any
|
|
140
|
+
declare function tool<Params extends z.ZodObject<any>, OutputSchema extends z.ZodObject<any>, Fact = never>(tool: Tool<Params, OutputSchema, Fact>): Tool<Params, OutputSchema, Fact>;
|
|
89
141
|
type InitData = {
|
|
90
142
|
clientInfo: Implementation;
|
|
91
143
|
clientCapabilities: ClientCapabilities;
|
|
92
144
|
};
|
|
93
145
|
type ToolCallBaseDetails = {
|
|
146
|
+
/**
|
|
147
|
+
* The tool name the client sent. It may not be a registered tool, so it is
|
|
148
|
+
* an unbounded, client-chosen value: don't use it as a metric label as-is.
|
|
149
|
+
*/
|
|
94
150
|
name: string;
|
|
95
151
|
arguments: Record<string, unknown>;
|
|
152
|
+
/** Absent for unknown tools. */
|
|
96
153
|
annotations?: Annotations;
|
|
97
154
|
};
|
|
98
155
|
type ToolCallSuccessDetails = ToolCallBaseDetails & {
|
|
@@ -108,7 +165,7 @@ type InitCallback = (initData: InitData) => void | Promise<void>;
|
|
|
108
165
|
type ToolCallCallback = (details: ToolCallDetails) => void;
|
|
109
166
|
type PropCallback<T> = () => T | Promise<T>;
|
|
110
167
|
type Prop<T> = T | PropCallback<T>;
|
|
111
|
-
type McpServerOptions = {
|
|
168
|
+
type McpServerOptions<Bucket extends string = never, Fact = never> = {
|
|
112
169
|
/**
|
|
113
170
|
* The name of the MCP server. This will be sent to the client as part of
|
|
114
171
|
* the initialization process.
|
|
@@ -161,7 +218,7 @@ type McpServerOptions = {
|
|
|
161
218
|
* asks for the list of tools or invokes a tool. This allows for dynamic tools
|
|
162
219
|
* that can change after the server has started.
|
|
163
220
|
*/
|
|
164
|
-
tools?: Record<string, Tool
|
|
221
|
+
tools?: Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>> | ((ctx?: ServerContext) => Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>> | Promise<Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>>);
|
|
165
222
|
/**
|
|
166
223
|
* Multi-round-trip `requestState` integrity hook (protocol revision
|
|
167
224
|
* 2026-07-28), passed straight through to the underlying SDK `Server`.
|
|
@@ -173,6 +230,9 @@ type McpServerOptions = {
|
|
|
173
230
|
requestState?: {
|
|
174
231
|
verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;
|
|
175
232
|
};
|
|
233
|
+
/** Optional per-request observer; see ObservedMethod for covered handlers. */
|
|
234
|
+
observer?: RequestObserver<Bucket, Fact>;
|
|
235
|
+
classifyTool?: (name: string) => Bucket | 'other';
|
|
176
236
|
};
|
|
177
237
|
/**
|
|
178
238
|
* Creates an MCP server with the given options.
|
|
@@ -180,7 +240,7 @@ type McpServerOptions = {
|
|
|
180
240
|
* Simplifies the process of creating an MCP server by providing a high-level
|
|
181
241
|
* API for defining resources and tools.
|
|
182
242
|
*/
|
|
183
|
-
declare function createMcpServer(options: McpServerOptions): Server;
|
|
243
|
+
declare function createMcpServer<Bucket extends string = never, Fact = never>(options: McpServerOptions<Bucket, Fact>): Server;
|
|
184
244
|
|
|
185
245
|
/**
|
|
186
246
|
* An MCP transport built on top of a duplex stream.
|
|
@@ -202,4 +262,4 @@ declare class StreamTransport implements Transport, DuplexStream<JSONRPCMessage>
|
|
|
202
262
|
close(): Promise<void>;
|
|
203
263
|
}
|
|
204
264
|
|
|
205
|
-
export { type Annotations, type DuplexStream, type ExtractParams, type InitCallback, type InitData, type McpServerOptions, type Prop, type PropCallback, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, type ToolCallCallback, type ToolCallDetails, createMcpServer, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
|
|
265
|
+
export { type Annotations, type DuplexStream, type ExtractParams, type InitCallback, type InitData, type McpServerOptions, type ObservationContext, type ObservationEnd, type ObservedMethod, type Prop, type PropCallback, type RequestObservation, type RequestObserver, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, type ToolCallCallback, type ToolCallDetails, ToolCallerError, type ToolCallerErrorKind, type ToolObservation, type ToolOutcome, createMcpServer, isToolCallerError, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isCallToolResult as
|
|
1
|
+
var g=Symbol.for("supabase.mcp.callerError"),T=class extends Error{constructor(t,r){super(t,r),this.name="ToolCallerError",this[g]=!0,r?.kind!==void 0&&(this.kind=r.kind)}};function F(e){return typeof e=="object"&&e!==null&&g in e&&e[g]===!0}import{isCallToolResult as z,Server as M}from"@modelcontextprotocol/server";import{z as B}from"zod/v4";function C(e){try{return new URL(e),e}catch{throw new Error(`invalid uri: ${e}`)}}function S(e,t){let r=new URL(e),o=new URL(t);return r.href===o.href}function P(e,t){let o=new URL(e).pathname.split("/").slice(1);for(let m of t){let l=new URL(m),n=decodeURIComponent(l.pathname).split("/").slice(1);if(o.length!==n.length)continue;let s={},i=!0;for(let c=0;c<o.length;c++){let a=n[c],d=o[c];if(!a||!d)break;if(a.startsWith("{")&&a.endsWith("}")){let f=a.slice(1,-1);if(!f)break;s[f]=d}else if(o[c]!==n[c]){i=!1;break}}if(i)return{uri:m,params:s}}}function O(e,t){if(!e)return;let r=performance.now(),o;try{if(o=e(t),o&&"then"in o&&typeof o.then=="function"){Promise.resolve(o).catch(()=>{});return}}catch{return}if(!o)return;let m=!1,l="completed";return{tool:{record(n){m||E(()=>o.record(n))},setOutcome(n){m||(l=n)}},end(n){if(m)return;m=!0;let s=performance.now()-r;E(()=>o.end({result:n,durationMs:s}))},outcome:()=>l}}function E(e){try{Promise.resolve(e()).catch(()=>{})}catch{}}function W(e,t){return{uri:e,...t}}function H(e,t){return{uriTemplate:e,...t}}function K(e,t){return{uri:e,mimeType:"application/json",...t}}function V(e,t){return{uriTemplate:e,mimeType:"application/json",...t}}function G(e,t){return t.map(r=>{if("uri"in r){let l=new URL(r.uri,`${e}://`),n=decodeURI(l.href);return{...r,uri:n}}let o=new URL(r.uriTemplate,`${e}://`),m=decodeURI(o.href);return{...r,uriTemplate:m}})}function Q(e,t){return{uri:e,mimeType:"application/json",text:JSON.stringify(t)}}function X(e){return e}function Y(e){let t={};e.resources&&(t.resources={}),e.tools&&(t.tools={});let r=new M({name:e.name,title:e.title,version:e.version},{capabilities:t,instructions:e.instructions,requestState:e.requestState});async function o(){if(!e.resources)throw new Error("resources not available");return typeof e.resources=="function"?await e.resources():e.resources}async function m(n){if(!e.tools)throw new Error("tools not available");return typeof e.tools=="function"?await e.tools(n):e.tools}async function l(n,s){let i=O(e.observer,{method:n}),c="handler_error";try{let a=await s();return c="isError"in a&&a.isError===!0?"tool_error":"completed",a}finally{i?.end(c)}}return r.oninitialized=async()=>{let n=r.getClientVersion(),s=r.getClientCapabilities();if(!n)throw new Error("client info not available after initialization");if(!s)throw new Error("client capabilities not available after initialization");let i={clientInfo:n,clientCapabilities:s};await e.onInitialize?.(i)},e.resources&&(r.setRequestHandler("resources/list",()=>l("resources/list",async()=>({resources:(await o()).filter(s=>"uri"in s).map(({uri:s,name:i,description:c,mimeType:a})=>({uri:s,name:i,description:c,mimeType:a}))}))),r.setRequestHandler("resources/templates/list",()=>l("resources/templates/list",async()=>({resourceTemplates:(await o()).filter(s=>"uriTemplate"in s).map(({uriTemplate:s,name:i,description:c,mimeType:a})=>({uriTemplate:s,name:i,description:c,mimeType:a}))}))),r.setRequestHandler("resources/read",n=>l("resources/read",async()=>{try{let s=await o(),{uri:i}=n.params,a=s.filter(u=>"uri"in u).find(u=>S(u.uri,i));if(a){let u=await a.read(i);return{contents:Array.isArray(u)?u:[u]}}let d=s.filter(u=>"uriTemplate"in u),f=d.map(({uriTemplate:u})=>C(u)),p=P(i,f);if(!p)throw new Error("resource not found");let R=d.find(u=>u.uriTemplate===p.uri);if(!R)throw new Error("resource not found");let y=await R.read(i,p.params);return{contents:Array.isArray(y)?y:[y]}}catch(s){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:k(s)})}]}}}))),e.tools&&(r.setRequestHandler("tools/list",(n,s)=>l("tools/list",async()=>{let i=await m(s);return{tools:await Promise.all(Object.entries(i).filter(([,c])=>!c.hidden).map(async([c,{description:a,annotations:d,parameters:f}])=>{let p=B.toJSONSchema(f,{target:"draft-7"});return{name:c,description:typeof a=="function"?await a():a,annotations:d,inputSchema:p}}))}})),r.setRequestHandler("tools/call",async(n,s)=>{let i=n.params.name,c="other";if(e.observer)try{c=e.classifyTool?.(i)??"other"}catch{}let a=O(e.observer,{method:"tools/call",tool:c}),d="handler_error",f=p=>{try{e.onToolCall?.(p)}catch(R){console.error("Failed to run tool callback",R)}};try{let p=await m(s),R=n.params.arguments??{},y=p[i];if(!y)throw f({name:i,arguments:R,success:!1,error:new T("tool not found")}),new Error("tool not found");let v=y.parameters.strict().safeParse(R);if(!v.success)throw f({name:i,arguments:R,annotations:y.annotations,success:!1,error:new T(v.error.message,{cause:v.error})}),v.error;let u=v.data,b=await(async w=>{let x=await w.execute(u,s,a?.tool).then(h=>({success:!0,data:h})).catch(h=>({success:!1,error:h}));if(f({name:i,arguments:u,annotations:w.annotations,...x}),!x.success)throw x.error;return x.data})(y);if(D(b))return d="input_required",b;if(z(b))return d=b.isError?"tool_error":a?.outcome()??"completed",b;let q=b!=null?[{type:"text",text:JSON.stringify(b)}]:[];return d=a?.outcome()??"completed",{content:q}}catch(p){let R={isError:!0,content:[{type:"text",text:JSON.stringify({error:k(p)})}]};return d="tool_error",R}finally{a?.end(d)}})),r}function D(e){return typeof e=="object"&&e!==null&&e.resultType==="input_required"}function k(e){if(!e||typeof e!="object")return e;let t={},r=["name","message"];for(let o of r)o in e&&(t[o]=e[o]);return t}var U=class{#e;#t;ready;readable;writable;onclose;onerror;onmessage;constructor(){let t,r,o=new Promise(l=>{t=l}),m=new Promise(l=>{r=l});this.ready=Promise.all([o,m]).then(()=>{}),this.readable=new ReadableStream({start:l=>{this.#e=l,t()}}),this.writable=new WritableStream({start:l=>{this.#t=l,r()},write:l=>{this.onmessage?.(l)}})}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{U as StreamTransport,T as ToolCallerError,Y as createMcpServer,F as isToolCallerError,K as jsonResource,Q as jsonResourceResponse,V as jsonResourceTemplate,W as resource,H as resourceTemplate,G as resources,X 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 { 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,U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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"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/server.ts","../src/util.ts","../src/observation.ts","../src/stream-transport.ts"],"sourcesContent":["const toolCallerErrorBrand = Symbol.for('supabase.mcp.callerError');\n\n/**\n * What a caller error asks of the caller. `confirmation_required` means the\n * tool needs a confirmation step first: a mismatched `confirm_cost_id`, or a\n * missing one when inline cost confirmation is configured. Without it, the\n * schema check rejects a missing `confirm_cost_id` first, and the error has a\n * `ZodError` cause and no kind.\n */\nexport type ToolCallerErrorKind = 'confirmation_required';\n\n/**\n * A tool error caused by the caller's input, comparable to an HTTP 4xx.\n */\nexport class ToolCallerError extends Error {\n declare [toolCallerErrorBrand]: true;\n declare readonly kind?: ToolCallerErrorKind;\n\n constructor(\n message: string,\n options?: ErrorOptions & { kind?: ToolCallerErrorKind }\n ) {\n super(message, options);\n this.name = 'ToolCallerError';\n // Assigned here because a class field initializer miscompiles in the CJS build.\n this[toolCallerErrorBrand] = true;\n if (options?.kind !== undefined) {\n this.kind = options.kind;\n }\n }\n}\n\n/**\n * Checks the global symbol brand so errors from another installed copy of this package still match.\n */\nexport function isToolCallerError(error: unknown): error is ToolCallerError {\n return (\n typeof error === 'object' &&\n error !== null &&\n toolCallerErrorBrand in error &&\n error[toolCallerErrorBrand] === true\n );\n}\n","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 { ToolCallerError } from './errors.js';\nimport type { ExtractParams } from './types.js';\nimport { assertValidUri, compareUris, matchUriTemplate } from './util.js';\nimport { beginObservation } from './observation.js';\nimport type {\n ObservationEnd,\n ObservedMethod,\n ToolObservation,\n RequestObserver,\n} from './observation.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 Fact = never,\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 * The optional observation handle records custom facts and sets an explicit\n * outcome. Its methods isolate sink failures and become inert after settlement.\n */\n execute: (\n params: z.infer<Params>,\n ctx: ServerContext,\n observation?: ToolObservation<Fact>\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 Fact = never,\n>(tool: Tool<Params, OutputSchema, Fact>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n /**\n * The tool name the client sent. It may not be a registered tool, so it is\n * an unbounded, client-chosen value: don't use it as a metric label as-is.\n */\n name: string;\n arguments: Record<string, unknown>;\n /** Absent for unknown tools. */\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<Bucket extends string = never, Fact = never> = {\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<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n | ((\n ctx?: ServerContext\n ) =>\n | Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n | Promise<\n Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n >);\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 /** Optional per-request observer; see ObservedMethod for covered handlers. */\n observer?: RequestObserver<Bucket, Fact>;\n classifyTool?: (name: string) => Bucket | 'other';\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<Bucket extends string = never, Fact = never>(\n options: McpServerOptions<Bucket, Fact>\n) {\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 async function observed<Result extends object>(\n method: Exclude<ObservedMethod, 'tools/call'>,\n run: () => Promise<Result>\n ): Promise<Result> {\n const scope = beginObservation(options.observer, { method });\n let outcome: ObservationEnd['result'] = 'handler_error';\n try {\n const result = await run();\n outcome =\n 'isError' in result && result.isError === true\n ? 'tool_error'\n : 'completed';\n return result;\n } finally {\n scope?.end(outcome);\n }\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 (): Promise<ListResourcesResult> =>\n observed('resources/list', async () => {\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 (): Promise<ListResourceTemplatesResult> =>\n observed('resources/templates/list', async () => {\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 (request): Promise<ReadResourceResult> =>\n observed('resources/read', async () => {\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(\n uri as `${string}://${string}`\n );\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 // Preserve the existing resource error payload despite the SDK result type.\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } as unknown as ReadResourceResult;\n }\n })\n );\n }\n\n if (options.tools) {\n server.setRequestHandler(\n 'tools/list',\n (_request, ctx): Promise<ListToolsResult> =>\n observed('tools/list', async () => {\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(\n 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 ),\n } satisfies ListToolsResult;\n })\n );\n\n server.setRequestHandler('tools/call', async (request, ctx) => {\n const toolName = request.params.name;\n let tool: Bucket | 'other' = 'other';\n if (options.observer) {\n try {\n tool = options.classifyTool?.(toolName) ?? 'other';\n } catch {}\n }\n const scope = beginObservation(options.observer, {\n method: 'tools/call',\n tool,\n });\n let outcome: ObservationEnd['result'] = 'handler_error';\n\n const reportToolCall = (details: ToolCallDetails) => {\n try {\n options.onToolCall?.(details);\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\n try {\n const tools = await getTools(ctx);\n const rawArgs = request.params.arguments ?? {};\n const tool = tools[toolName];\n\n // The client still sees the original error; the hook gets a caller error.\n if (!tool) {\n reportToolCall({\n name: toolName,\n arguments: rawArgs,\n success: false,\n error: new ToolCallerError('tool not found'),\n });\n throw new Error('tool not found');\n }\n\n const parsed = tool.parameters.strict().safeParse(rawArgs);\n if (!parsed.success) {\n reportToolCall({\n name: toolName,\n arguments: rawArgs,\n annotations: tool.annotations,\n success: false,\n error: new ToolCallerError(parsed.error.message, {\n cause: parsed.error,\n }),\n });\n throw parsed.error;\n }\n const args = parsed.data;\n\n const executeWithCallback = async (\n tool: Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>\n ) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args, ctx, scope?.tool)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n reportToolCall({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\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 is already shaped for the wire.\n if (isInputRequiredResult(result)) {\n outcome = 'input_required';\n return result;\n }\n\n // A direct CallToolResult is already shaped for the wire; pass it\n // through instead of JSON-wrapping it.\n if (isCallToolResult(result)) {\n outcome = result.isError\n ? 'tool_error'\n : (scope?.outcome() ?? 'completed');\n return result;\n }\n\n const content =\n result != null\n ? [{ type: 'text' as const, text: JSON.stringify(result) }]\n : [];\n\n outcome = scope?.outcome() ?? 'completed';\n return {\n content,\n };\n } catch (error) {\n const result = {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } satisfies CallToolResult;\n outcome = 'tool_error';\n return result;\n } finally {\n scope?.end(outcome);\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","/** Observations describe handler attempts, not transport delivery or backend commit. */\nexport type ObservedMethod =\n | 'tools/call'\n | 'tools/list'\n | 'resources/list'\n | 'resources/templates/list'\n | 'resources/read';\n\nexport type ObservationContext<Bucket extends string = never> =\n | Readonly<{ method: 'tools/call'; tool: Bucket | 'other' }>\n | Readonly<{ method: Exclude<ObservedMethod, 'tools/call'> }>;\n\nexport type ToolOutcome = 'completed' | 'declined' | 'cancelled';\n\nexport type ToolObservation<Fact = never> = Readonly<{\n record: (fact: Fact) => void;\n setOutcome: (result: ToolOutcome) => void;\n}>;\n\nexport type ObservationEnd = Readonly<{\n result: ToolOutcome | 'input_required' | 'tool_error' | 'handler_error';\n durationMs: number;\n}>;\n\n/** Sink failures are isolated; custom facts remain the producer's responsibility. */\nexport type RequestObservation<Fact = never> = Readonly<{\n record: (fact: Fact) => void | Promise<void>;\n end: (result: ObservationEnd) => void | Promise<void>;\n}>;\n\n/** Synchronous factory; promises and thenables are unsupported. */\nexport type RequestObserver<Bucket extends string = never, Fact = never> = (\n context: ObservationContext<Bucket>\n) => RequestObservation<Fact> | undefined;\n\n/** Package-internal lifecycle controls are never passed to a tool. */\nexport type ObservationScope<Fact = never> = Readonly<{\n tool: ToolObservation<Fact>;\n end: (result: ObservationEnd['result']) => void;\n outcome: () => ToolOutcome;\n}>;\n\n/**\n * Factory and sink failures are contained, never awaited or logged.\n * Synchronous callbacks can still block; this is not a CPU sandbox.\n */\nexport function beginObservation<Bucket extends string = never, Fact = never>(\n observer: RequestObserver<Bucket, Fact> | undefined,\n context: ObservationContext<Bucket>\n): ObservationScope<Fact> | undefined {\n if (!observer) return undefined;\n const start = performance.now();\n let observation: RequestObservation<Fact> | undefined;\n try {\n observation = observer(context);\n if (\n observation &&\n 'then' in observation &&\n typeof observation.then === 'function'\n ) {\n void Promise.resolve(observation).catch(() => {});\n return undefined;\n }\n } catch {\n return undefined;\n }\n if (!observation) return undefined;\n\n let ended = false;\n let outcome: ToolOutcome = 'completed';\n return {\n tool: {\n record(fact): void {\n if (!ended) safeCall(() => observation.record(fact));\n },\n setOutcome(result): void {\n if (!ended) outcome = result;\n },\n },\n end(result): void {\n if (ended) return;\n ended = true;\n const durationMs = performance.now() - start;\n safeCall(() => observation.end({ result, durationMs }));\n },\n outcome: () => outcome,\n };\n}\n\nfunction safeCall(action: () => void | Promise<void>): void {\n try {\n void Promise.resolve(action()).catch(() => {});\n } catch {\n // Telemetry-only failure: never surface, retry, or log the raw value.\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,IAAMA,EAAuB,OAAO,IAAI,0BAA0B,EAcrDC,EAAN,cAA8B,KAAM,CAIzC,YACEC,EACAC,EACA,CACA,MAAMD,EAASC,CAAO,EACtB,KAAK,KAAO,kBAEZ,KAAKH,CAAoB,EAAI,GACzBG,GAAS,OAAS,SACpB,KAAK,KAAOA,EAAQ,KAExB,CACF,EAKO,SAASC,EAAkBC,EAA0C,CAC1E,OACE,OAAOA,GAAU,UACjBA,IAAU,MACVL,KAAwBK,GACxBA,EAAML,CAAoB,IAAM,EAEpC,CC1CA,OAAS,oBAAAM,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,CAAI,EACnBG,EAAO,IAAI,IAAIF,CAAI,EAEzB,OAAOC,EAAK,OAASC,EAAK,IAC5B,CAQO,SAASC,EACdN,EACAO,EAMY,CAEZ,IAAMC,E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ACH,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":["toolCallerErrorBrand","ToolCallerError","message","options","isToolCallerError","error","isCallToolResult","Server","z","assertValidUri","uri","compareUris","uriA","uriB","urlA","urlB","matchUriTemplate","uriTemplates","segments","resourceUri","resourceUrl","resourceSegments","params","isMatch","i","resourceSegment","segment","paramKey","beginObservation","observer","context","start","observation","ended","outcome","fact","safeCall","result","durationMs","action","resource","uri","resourceTemplate","uriTemplate","jsonResource","jsonResourceTemplate","resources","scheme","url","jsonResourceResponse","response","tool","createMcpServer","options","capabilities","server","Server","getResources","getTools","ctx","observed","method","run","scope","beginObservation","outcome","result","clientInfo","clientCapabilities","initData","name","description","mimeType","request","allResources","compareUris","resourceTemplates","resourceTemplateUris","assertValidUri","templateMatch","matchUriTemplate","r","error","enumerateError","_request","tools","annotations","parameters","inputSchema","z","toolName","reportToolCall","details","rawArgs","ToolCallerError","parsed","args","res","data","isInputRequiredResult","isCallToolResult","content","value","newError","errorProps","prop","StreamTransport","#readableStreamController","#writeableStreamController","resolveReadReady","resolveWriteReady","readReady","resolve","writeReady","controller","message"]}
|