@supabase/mcp-utils 0.5.1 → 0.6.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 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 _indexjs = require('@modelcontextprotocol/sdk/server/index.js');var _typesjs = require('@modelcontextprotocol/sdk/types.js');var _v4 = require('zod/v4');function g(e){try{return new URL(e),e}catch (e2){throw new Error(`invalid uri: ${e}`)}}function T(e,r){let o=new URL(e),a=new URL(r);return o.href===a.href}function h(e,r){let a=new URL(e).pathname.split("/").slice(1);for(let m of r){let s=new URL(m),t=decodeURIComponent(s.pathname).split("/").slice(1);if(a.length!==t.length)continue;let n={},l=!0;for(let i=0;i<a.length;i++){let u=t[i],R=a[i];if(!u||!R)break;if(u.startsWith("{")&&u.endsWith("}")){let f=u.slice(1,-1);if(!f)break;n[f]=R}else if(a[i]!==t[i]){l=!1;break}}if(l)return{uri:m,params:n}}}function L(e,r){return{uri:e,...r}}function z(e,r){return{uriTemplate:e,...r}}function q(e,r){return{uri:e,mimeType:"application/json",...r}}function I(e,r){return{uriTemplate:e,mimeType:"application/json",...r}}function M(e,r){return r.map(o=>{if("uri"in o){let s=new URL(o.uri,`${e}://`),t=decodeURI(s.href);return{...o,uri:t}}let a=new URL(o.uriTemplate,`${e}://`),m=decodeURI(a.href);return{...o,uriTemplate:m}})}function J(e,r){return{uri:e,mimeType:"application/json",text:JSON.stringify(r)}}function A(e){return e}function W(e){let r={};e.resources&&(r.resources={}),e.tools&&(r.tools={});let o=new (0, _indexjs.Server)({name:e.name,title:e.title,version:e.version},{capabilities:r,instructions:e.instructions});async function a(){if(!e.resources)throw new Error("resources not available");return typeof e.resources=="function"?await e.resources():e.resources}async function m(){if(!e.tools)throw new Error("tools not available");return typeof e.tools=="function"?await e.tools():e.tools}return o.oninitialized=async()=>{let s=o.getClientVersion(),t=o.getClientCapabilities();if(!s)throw new Error("client info not available after initialization");if(!t)throw new Error("client capabilities not available after initialization");let n={clientInfo:s,clientCapabilities:t};await _optionalChain([e, 'access', _ => _.onInitialize, 'optionalCall', _2 => _2(n)])},e.resources&&(o.setRequestHandler(_typesjs.ListResourcesRequestSchema,async()=>({resources:(await a()).filter(t=>"uri"in t).map(({uri:t,name:n,description:l,mimeType:i})=>({uri:t,name:n,description:l,mimeType:i}))})),o.setRequestHandler(_typesjs.ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:(await a()).filter(t=>"uriTemplate"in t).map(({uriTemplate:t,name:n,description:l,mimeType:i})=>({uriTemplate:t,name:n,description:l,mimeType:i}))})),o.setRequestHandler(_typesjs.ReadResourceRequestSchema,async s=>{try{let t=await a(),{uri:n}=s.params,i=t.filter(c=>"uri"in c).find(c=>T(c.uri,n));if(i){let c=await i.read(n);return{contents:Array.isArray(c)?c:[c]}}let u=t.filter(c=>"uriTemplate"in c),R=u.map(({uriTemplate:c})=>g(c)),f=h(n,R);if(!f)throw new Error("resource not found");let y=u.find(c=>c.uriTemplate===f.uri);if(!y)throw new Error("resource not found");let p=await y.read(n,f.params);return{contents:Array.isArray(p)?p:[p]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:x(t)})}]}}})),e.tools&&(o.setRequestHandler(_typesjs.ListToolsRequestSchema,async()=>{let s=await m();return{tools:await Promise.all(Object.entries(s).map(async([t,{description:n,annotations:l,parameters:i}])=>{let u=_v4.z.toJSONSchema(i,{target:"draft-7"});return{name:t,description:typeof n=="function"?await n():n,annotations:l,inputSchema:u}}))}}),o.setRequestHandler(_typesjs.CallToolRequestSchema,async s=>{try{let t=await m(),n=s.params.name;if(!(n in t))throw new Error("tool not found");let l=t[n];if(!l)throw new Error("tool not found");let i=l.parameters.strict().parse(_nullishCoalesce(s.params.arguments, () => ({}))),R=await(async y=>{let p=await y.execute(i).then(d=>({success:!0,data:d})).catch(d=>({success:!1,error:d}));try{_optionalChain([e, 'access', _3 => _3.onToolCall, 'optionalCall', _4 => _4({name:n,arguments:i,annotations:y.annotations,...p})])}catch(d){console.error("Failed to run tool callback",d)}if(!p.success)throw p.error;return p.data})(l);return{content:R!=null?[{type:"text",text:JSON.stringify(R)}]:[]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:x(t)})}]}}})),o}function x(e){if(!e||typeof e!="object")return e;let r={},o=["name","message"];for(let a of o)a in e&&(r[a]=e[a]);return r}var w=class{#e;#t;constructor(){let r,o,a=new Promise(s=>{r=s}),m=new Promise(s=>{o=s});this.ready=Promise.all([a,m]).then(()=>{}),this.readable=new ReadableStream({start:s=>{this.#e=s,r()}}),this.writable=new WritableStream({start:s=>{this.#t=s,o()},write:s=>{_optionalChain([this, 'access', _5 => _5.onmessage, 'optionalCall', _6 => _6(s)])}})}async start(){await this.ready}async send(r){if(!this.#e)throw new Error("readable stream not initialized");this.#e.enqueue(r)}async close(){_optionalChain([this, 'access', _7 => _7.#e, 'optionalAccess', _8 => _8.error, 'call', _9 => _9(new Error("connection closed"))]),_optionalChain([this, 'access', _10 => _10.#t, 'optionalAccess', _11 => _11.error, 'call', _12 => _12(new Error("connection closed"))]),_optionalChain([this, 'access', _13 => _13.onclose, 'optionalCall', _14 => _14()])}};exports.StreamTransport = w; exports.createMcpServer = W; exports.jsonResource = q; exports.jsonResourceResponse = J; exports.jsonResourceTemplate = I; exports.resource = L; exports.resourceTemplate = z; exports.resources = M; exports.tool = A;
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 _indexjs = require('@modelcontextprotocol/sdk/server/index.js');var _typesjs = require('@modelcontextprotocol/sdk/types.js');var _v4 = require('zod/v4');function g(e){try{return new URL(e),e}catch (e2){throw new Error(`invalid uri: ${e}`)}}function T(e,r){let o=new URL(e),a=new URL(r);return o.href===a.href}function h(e,r){let a=new URL(e).pathname.split("/").slice(1);for(let m of r){let s=new URL(m),t=decodeURIComponent(s.pathname).split("/").slice(1);if(a.length!==t.length)continue;let n={},l=!0;for(let i=0;i<a.length;i++){let u=t[i],R=a[i];if(!u||!R)break;if(u.startsWith("{")&&u.endsWith("}")){let d=u.slice(1,-1);if(!d)break;n[d]=R}else if(a[i]!==t[i]){l=!1;break}}if(l)return{uri:m,params:n}}}function L(e,r){return{uri:e,...r}}function z(e,r){return{uriTemplate:e,...r}}function q(e,r){return{uri:e,mimeType:"application/json",...r}}function I(e,r){return{uriTemplate:e,mimeType:"application/json",...r}}function M(e,r){return r.map(o=>{if("uri"in o){let s=new URL(o.uri,`${e}://`),t=decodeURI(s.href);return{...o,uri:t}}let a=new URL(o.uriTemplate,`${e}://`),m=decodeURI(a.href);return{...o,uriTemplate:m}})}function J(e,r){return{uri:e,mimeType:"application/json",text:JSON.stringify(r)}}function A(e){return e}function W(e){let r={};e.resources&&(r.resources={}),e.tools&&(r.tools={});let o=new (0, _indexjs.Server)({name:e.name,title:e.title,version:e.version},{capabilities:r,instructions:e.instructions});async function a(){if(!e.resources)throw new Error("resources not available");return typeof e.resources=="function"?await e.resources():e.resources}async function m(){if(!e.tools)throw new Error("tools not available");return typeof e.tools=="function"?await e.tools():e.tools}return o.oninitialized=async()=>{let s=o.getClientVersion(),t=o.getClientCapabilities();if(!s)throw new Error("client info not available after initialization");if(!t)throw new Error("client capabilities not available after initialization");let n={clientInfo:s,clientCapabilities:t};await _optionalChain([e, 'access', _ => _.onInitialize, 'optionalCall', _2 => _2(n)])},e.resources&&(o.setRequestHandler(_typesjs.ListResourcesRequestSchema,async()=>({resources:(await a()).filter(t=>"uri"in t).map(({uri:t,name:n,description:l,mimeType:i})=>({uri:t,name:n,description:l,mimeType:i}))})),o.setRequestHandler(_typesjs.ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:(await a()).filter(t=>"uriTemplate"in t).map(({uriTemplate:t,name:n,description:l,mimeType:i})=>({uriTemplate:t,name:n,description:l,mimeType:i}))})),o.setRequestHandler(_typesjs.ReadResourceRequestSchema,async s=>{try{let t=await a(),{uri:n}=s.params,i=t.filter(c=>"uri"in c).find(c=>T(c.uri,n));if(i){let c=await i.read(n);return{contents:Array.isArray(c)?c:[c]}}let u=t.filter(c=>"uriTemplate"in c),R=u.map(({uriTemplate:c})=>g(c)),d=h(n,R);if(!d)throw new Error("resource not found");let y=u.find(c=>c.uriTemplate===d.uri);if(!y)throw new Error("resource not found");let p=await y.read(n,d.params);return{contents:Array.isArray(p)?p:[p]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:x(t)})}]}}})),e.tools&&(o.setRequestHandler(_typesjs.ListToolsRequestSchema,async()=>{let s=await m();return{tools:await Promise.all(Object.entries(s).filter(([,t])=>!t.hidden).map(async([t,{description:n,annotations:l,parameters:i}])=>{let u=_v4.z.toJSONSchema(i,{target:"draft-7"});return{name:t,description:typeof n=="function"?await n():n,annotations:l,inputSchema:u}}))}}),o.setRequestHandler(_typesjs.CallToolRequestSchema,async s=>{try{let t=await m(),n=s.params.name;if(!(n in t))throw new Error("tool not found");let l=t[n];if(!l)throw new Error("tool not found");let i=l.parameters.strict().parse(_nullishCoalesce(s.params.arguments, () => ({}))),R=await(async y=>{let p=await y.execute(i).then(f=>({success:!0,data:f})).catch(f=>({success:!1,error:f}));try{_optionalChain([e, 'access', _3 => _3.onToolCall, 'optionalCall', _4 => _4({name:n,arguments:i,annotations:y.annotations,...p})])}catch(f){console.error("Failed to run tool callback",f)}if(!p.success)throw p.error;return p.data})(l);return{content:R!=null?[{type:"text",text:JSON.stringify(R)}]:[]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:x(t)})}]}}})),o}function x(e){if(!e||typeof e!="object")return e;let r={},o=["name","message"];for(let a of o)a in e&&(r[a]=e[a]);return r}var w=class{#e;#t;constructor(){let r,o,a=new Promise(s=>{r=s}),m=new Promise(s=>{o=s});this.ready=Promise.all([a,m]).then(()=>{}),this.readable=new ReadableStream({start:s=>{this.#e=s,r()}}),this.writable=new WritableStream({start:s=>{this.#t=s,o()},write:s=>{_optionalChain([this, 'access', _5 => _5.onmessage, 'optionalCall', _6 => _6(s)])}})}async start(){await this.ready}async send(r){if(!this.#e)throw new Error("readable stream not initialized");this.#e.enqueue(r)}async close(){_optionalChain([this, 'access', _7 => _7.#e, 'optionalAccess', _8 => _8.error, 'call', _9 => _9(new Error("connection closed"))]),_optionalChain([this, 'access', _10 => _10.#t, 'optionalAccess', _11 => _11.error, 'call', _12 => _12(new Error("connection closed"))]),_optionalChain([this, 'access', _13 => _13.onclose, 'optionalCall', _14 => _14()])}};exports.StreamTransport = w; exports.createMcpServer = W; exports.jsonResource = q; exports.jsonResourceResponse = J; exports.jsonResourceTemplate = I; exports.resource = L; exports.resourceTemplate = z; exports.resources = M; exports.tool = A;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts","../src/util.ts"],"names":["assertValidUri","uri"],"mappings":"AAAA,qvBAAuB,6DAehB,4BACW,SCXFA,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":"/Users/matt/Developer/supabase-org/supabase-mcp/packages/mcp-utils/dist/index.cjs","sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport {\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n ReadResourceRequestSchema,\n type ClientCapabilities,\n type Implementation,\n type ListResourcesResult,\n type ListResourceTemplatesResult,\n type ReadResourceResult,\n type ServerCapabilities,\n type ListToolsResult,\n type Tool as McpTool,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod/v4';\nimport type {\n ExpandRecursively,\n ExtractNotification,\n ExtractParams,\n ExtractRequest,\n ExtractResult,\n} 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 execute(params: z.infer<Params>): Promise<z.infer<OutputSchema>>;\n};\n\n/**\n * Helper function to define an MCP resource while preserving type information.\n */\nexport function resource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri'>\n): Resource<Uri, Result> {\n return {\n uri,\n ...resource,\n };\n}\n\n/**\n * Helper function to define an MCP resource with a URI template while preserving type information.\n */\nexport function resourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource while preserving type information.\n */\nexport function jsonResource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>\n): Resource<Uri, Result> {\n return {\n uri,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource with a URI template while preserving type information.\n */\nexport function jsonResourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a list of resources that share a common URI scheme.\n */\nexport function resources<Scheme extends string>(\n scheme: Scheme,\n resources: (Resource | ResourceTemplate)[]\n): (\n | Resource<`${Scheme}://${string}`>\n | ResourceTemplate<`${Scheme}://${string}`>\n)[] {\n return resources.map((resource) => {\n if ('uri' in resource) {\n const url = new URL(resource.uri, `${scheme}://`);\n const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`;\n\n return {\n ...resource,\n uri,\n };\n }\n\n const url = new URL(resource.uriTemplate, `${scheme}://`);\n const uriTemplate = decodeURI(\n url.href\n ) as `${Scheme}://${typeof resource.uriTemplate}`;\n\n return {\n ...resource,\n uriTemplate,\n };\n });\n}\n\n/**\n * Helper function to create a JSON resource response.\n */\nexport function jsonResourceResponse<Uri extends string, Response>(\n uri: Uri,\n response: Response\n) {\n return {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(response),\n };\n}\n\n/**\n * Helper function to define an MCP tool while preserving type information.\n */\nexport function tool<\n Params extends z.ZodObject<any>,\n OutputSchema extends z.ZodObject<any>,\n>(tool: Tool<Params, OutputSchema>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n name: string;\n arguments: Record<string, unknown>;\n annotations?: Annotations;\n};\n\ntype ToolCallSuccessDetails = ToolCallBaseDetails & {\n success: true;\n data: unknown;\n};\n\ntype ToolCallErrorDetails = ToolCallBaseDetails & {\n success: false;\n error: unknown;\n};\n\nexport type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;\n\nexport type InitCallback = (initData: InitData) => void | Promise<void>;\nexport type ToolCallCallback = (details: ToolCallDetails) => void;\nexport type PropCallback<T> = () => T | Promise<T>;\nexport type Prop<T> = T | PropCallback<T>;\n\nexport type McpServerOptions = {\n /**\n * The name of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n name: string;\n\n /**\n * The title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Optional instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions?: string;\n\n /**\n * Callback for after a tool is called.\n */\n onToolCall?: ToolCallCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?: Prop<Record<string, Tool>>;\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer(options: McpServerOptions) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n instructions: options.instructions,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools() {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools()\n : options.tools;\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n ListResourcesRequestSchema,\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 ListResourceTemplatesRequestSchema,\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 ReadResourceRequestSchema,\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 ListToolsRequestSchema,\n async (): Promise<ListToolsResult> => {\n const tools = await getTools();\n\n return {\n tools: await Promise.all(\n Object.entries(tools).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(CallToolRequestSchema, async (request) => {\n try {\n const tools = await getTools();\n const toolName = request.params.name;\n\n if (!(toolName in tools)) {\n throw new Error('tool not found');\n }\n\n const tool = tools[toolName];\n\n if (!tool) {\n throw new Error('tool not found');\n }\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const executeWithCallback = async (tool: Tool) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n try {\n options.onToolCall?.({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\n });\n } catch (error) {\n // Don't fail the tool call if the callback fails\n console.error('Failed to run tool callback', error);\n }\n\n // Unwrap result\n if (!res.success) {\n throw res.error;\n }\n return res.data;\n };\n\n const result = await executeWithCallback(tool);\n\n const content =\n result != null\n ? [{ type: 'text', 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 // Expand types recursively for better intellisense\n type Request = ExpandRecursively<ExtractRequest<typeof server>>;\n type Notification = ExpandRecursively<ExtractNotification<typeof server>>;\n type Result = ExpandRecursively<ExtractResult<typeof server>>;\n\n return server as Server<Request, Notification, Result>;\n}\n\nfunction enumerateError(error: unknown) {\n if (!error) {\n return error;\n }\n\n if (typeof error !== 'object') {\n return error;\n }\n\n const newError: Record<string, unknown> = {};\n\n const errorProps = ['name', 'message'] as const;\n\n for (const prop of errorProps) {\n if (prop in error) {\n newError[prop] = (error as Record<string, unknown>)[prop];\n }\n }\n\n return newError;\n}\n","import type { ExtractParams } from './types.js';\n\n/**\n * Asserts that a URI is valid.\n */\nexport function assertValidUri(uri: string) {\n try {\n new URL(uri);\n return uri;\n } catch {\n throw new Error(`invalid uri: ${uri}`);\n }\n}\n\n/**\n * Compares two URIs.\n */\nexport function compareUris(uriA: string, uriB: string): boolean {\n const urlA = new URL(uriA);\n const urlB = new URL(uriB);\n\n return urlA.href === urlB.href;\n}\n\n/**\n * Matches a URI to a RFC 6570 URI Template (resourceUris) and extracts\n * the parameters.\n *\n * Currently only supports simple string parameters.\n */\nexport function matchUriTemplate<Templates extends string[]>(\n uri: string,\n uriTemplates: Templates\n):\n | {\n uri: Templates[number];\n params: { [Param in ExtractParams<Templates[number]>]: string };\n }\n | undefined {\n const url = new URL(uri);\n const segments = url.pathname.split('/').slice(1);\n\n for (const resourceUri of uriTemplates) {\n const resourceUrl = new URL(resourceUri);\n const resourceSegments = decodeURIComponent(resourceUrl.pathname)\n .split('/')\n .slice(1);\n\n if (segments.length !== resourceSegments.length) {\n continue;\n }\n\n const params: Record<string, string> = {};\n let isMatch = true;\n\n for (let i = 0; i < segments.length; i++) {\n const resourceSegment = resourceSegments[i];\n const segment = segments[i];\n\n if (!resourceSegment || !segment) {\n break;\n }\n\n if (resourceSegment.startsWith('{') && resourceSegment.endsWith('}')) {\n const paramKey = resourceSegment.slice(1, -1);\n\n if (!paramKey) {\n break;\n }\n\n params[paramKey] = segment;\n } else if (segments[i] !== resourceSegments[i]) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n return {\n uri: resourceUri,\n params: params as {\n [Param in ExtractParams<Templates[number]>]: string;\n },\n };\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/server.ts","../src/util.ts"],"names":["assertValidUri","uri"],"mappings":"AAAA,qvBAAuB,6DAehB,4BACW,SCXFA,CAAAA,CAAeC,CAAAA,CAAa,CAC1C,GAAI,CACF,OAAA,IAAI,GAAA,CAAIA,CAAG,CAAA,CACJA,CACT,CAAA,UAAQ,CACN,MAAM,IAAI,KAAA,CAAM,CAAA,aAAA,EAAgBA,CAAG,CAAA,CAAA","file":"/home/runner/work/mcp/mcp/packages/mcp-utils/dist/index.cjs","sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport {\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n ReadResourceRequestSchema,\n type ClientCapabilities,\n type Implementation,\n type ListResourcesResult,\n type ListResourceTemplatesResult,\n type ReadResourceResult,\n type ServerCapabilities,\n type ListToolsResult,\n type Tool as McpTool,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod/v4';\nimport type {\n ExpandRecursively,\n ExtractNotification,\n ExtractParams,\n ExtractRequest,\n ExtractResult,\n} from './types.js';\nimport { assertValidUri, compareUris, matchUriTemplate } from './util.js';\n\nexport type Scheme = string;\nexport type Annotations = NonNullable<\n ListToolsResult['tools'][number]['annotations']\n>;\n\nexport type Resource<Uri extends string = string, Result = unknown> = {\n uri: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(uri: `${Scheme}://${Uri}`): Promise<Result>;\n};\n\nexport type ResourceTemplate<Uri extends string = string, Result = unknown> = {\n uriTemplate: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(\n uri: `${Scheme}://${Uri}`,\n params: {\n [Param in ExtractParams<Uri>]: string;\n }\n ): Promise<Result>;\n};\n\nexport type Tool<\n Params extends z.ZodObject<any> = z.ZodObject<any>,\n // MCP spec restricts outputSchema to type \"object\" at the root level:\n // https://modelcontextprotocol.io/specification/2025-11-25/schema#tool-outputschema\n OutputSchema extends z.ZodObject<any> = z.ZodObject<any>,\n> = {\n description: Prop<string>;\n annotations?: Annotations;\n parameters: Params;\n outputSchema: OutputSchema;\n /** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */\n hidden?: boolean;\n execute(params: z.infer<Params>): Promise<z.infer<OutputSchema>>;\n};\n\n/**\n * Helper function to define an MCP resource while preserving type information.\n */\nexport function resource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri'>\n): Resource<Uri, Result> {\n return {\n uri,\n ...resource,\n };\n}\n\n/**\n * Helper function to define an MCP resource with a URI template while preserving type information.\n */\nexport function resourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource while preserving type information.\n */\nexport function jsonResource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>\n): Resource<Uri, Result> {\n return {\n uri,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource with a URI template while preserving type information.\n */\nexport function jsonResourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a list of resources that share a common URI scheme.\n */\nexport function resources<Scheme extends string>(\n scheme: Scheme,\n resources: (Resource | ResourceTemplate)[]\n): (\n | Resource<`${Scheme}://${string}`>\n | ResourceTemplate<`${Scheme}://${string}`>\n)[] {\n return resources.map((resource) => {\n if ('uri' in resource) {\n const url = new URL(resource.uri, `${scheme}://`);\n const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`;\n\n return {\n ...resource,\n uri,\n };\n }\n\n const url = new URL(resource.uriTemplate, `${scheme}://`);\n const uriTemplate = decodeURI(\n url.href\n ) as `${Scheme}://${typeof resource.uriTemplate}`;\n\n return {\n ...resource,\n uriTemplate,\n };\n });\n}\n\n/**\n * Helper function to create a JSON resource response.\n */\nexport function jsonResourceResponse<Uri extends string, Response>(\n uri: Uri,\n response: Response\n) {\n return {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(response),\n };\n}\n\n/**\n * Helper function to define an MCP tool while preserving type information.\n */\nexport function tool<\n Params extends z.ZodObject<any>,\n OutputSchema extends z.ZodObject<any>,\n>(tool: Tool<Params, OutputSchema>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n name: string;\n arguments: Record<string, unknown>;\n annotations?: Annotations;\n};\n\ntype ToolCallSuccessDetails = ToolCallBaseDetails & {\n success: true;\n data: unknown;\n};\n\ntype ToolCallErrorDetails = ToolCallBaseDetails & {\n success: false;\n error: unknown;\n};\n\nexport type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;\n\nexport type InitCallback = (initData: InitData) => void | Promise<void>;\nexport type ToolCallCallback = (details: ToolCallDetails) => void;\nexport type PropCallback<T> = () => T | Promise<T>;\nexport type Prop<T> = T | PropCallback<T>;\n\nexport type McpServerOptions = {\n /**\n * The name of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n name: string;\n\n /**\n * The title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Optional instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions?: string;\n\n /**\n * Callback for after a tool is called.\n */\n onToolCall?: ToolCallCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?: Prop<Record<string, Tool>>;\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer(options: McpServerOptions) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n instructions: options.instructions,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools() {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools()\n : options.tools;\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n ListResourcesRequestSchema,\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 ListResourceTemplatesRequestSchema,\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 ReadResourceRequestSchema,\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 ListToolsRequestSchema,\n async (): Promise<ListToolsResult> => {\n const tools = await getTools();\n\n return {\n tools: await Promise.all(\n Object.entries(tools)\n .filter(([, tool]) => !tool.hidden)\n .map(async ([name, { description, annotations, parameters }]) => {\n const inputSchema = z.toJSONSchema(parameters, {\n target: 'draft-7',\n });\n\n return {\n name,\n description:\n typeof description === 'function'\n ? await description()\n : description,\n annotations,\n // Casting the same as the SDK does:\n // https://github.com/modelcontextprotocol/typescript-sdk/blob/fb07af810b51003c338dc4885a9e42f54519f9af/src/server/mcp.ts#L154\n inputSchema: inputSchema as McpTool['inputSchema'],\n };\n })\n ),\n } satisfies ListToolsResult;\n }\n );\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n try {\n const tools = await getTools();\n const toolName = request.params.name;\n\n if (!(toolName in tools)) {\n throw new Error('tool not found');\n }\n\n const tool = tools[toolName];\n\n if (!tool) {\n throw new Error('tool not found');\n }\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const executeWithCallback = async (tool: Tool) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n try {\n options.onToolCall?.({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\n });\n } catch (error) {\n // Don't fail the tool call if the callback fails\n console.error('Failed to run tool callback', error);\n }\n\n // Unwrap result\n if (!res.success) {\n throw res.error;\n }\n return res.data;\n };\n\n const result = await executeWithCallback(tool);\n\n const content =\n result != null\n ? [{ type: 'text', 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 // Expand types recursively for better intellisense\n type Request = ExpandRecursively<ExtractRequest<typeof server>>;\n type Notification = ExpandRecursively<ExtractNotification<typeof server>>;\n type Result = ExpandRecursively<ExtractResult<typeof server>>;\n\n return server as Server<Request, Notification, Result>;\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
@@ -62,6 +62,8 @@ type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema exten
62
62
  annotations?: Annotations;
63
63
  parameters: Params;
64
64
  outputSchema: OutputSchema;
65
+ /** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */
66
+ hidden?: boolean;
65
67
  execute(params: z.infer<Params>): Promise<z.infer<OutputSchema>>;
66
68
  };
67
69
  /**
package/dist/index.d.ts CHANGED
@@ -62,6 +62,8 @@ type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema exten
62
62
  annotations?: Annotations;
63
63
  parameters: Params;
64
64
  outputSchema: OutputSchema;
65
+ /** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */
66
+ hidden?: boolean;
65
67
  execute(params: z.infer<Params>): Promise<z.infer<OutputSchema>>;
66
68
  };
67
69
  /**
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{Server as S}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as b,ListResourcesRequestSchema as C,ListResourceTemplatesRequestSchema as U,ListToolsRequestSchema as P,ReadResourceRequestSchema as v}from"@modelcontextprotocol/sdk/types.js";import{z as E}from"zod/v4";function g(e){try{return new URL(e),e}catch{throw new Error(`invalid uri: ${e}`)}}function T(e,r){let o=new URL(e),a=new URL(r);return o.href===a.href}function h(e,r){let a=new URL(e).pathname.split("/").slice(1);for(let m of r){let s=new URL(m),t=decodeURIComponent(s.pathname).split("/").slice(1);if(a.length!==t.length)continue;let n={},l=!0;for(let i=0;i<a.length;i++){let u=t[i],R=a[i];if(!u||!R)break;if(u.startsWith("{")&&u.endsWith("}")){let f=u.slice(1,-1);if(!f)break;n[f]=R}else if(a[i]!==t[i]){l=!1;break}}if(l)return{uri:m,params:n}}}function L(e,r){return{uri:e,...r}}function z(e,r){return{uriTemplate:e,...r}}function q(e,r){return{uri:e,mimeType:"application/json",...r}}function I(e,r){return{uriTemplate:e,mimeType:"application/json",...r}}function M(e,r){return r.map(o=>{if("uri"in o){let s=new URL(o.uri,`${e}://`),t=decodeURI(s.href);return{...o,uri:t}}let a=new URL(o.uriTemplate,`${e}://`),m=decodeURI(a.href);return{...o,uriTemplate:m}})}function J(e,r){return{uri:e,mimeType:"application/json",text:JSON.stringify(r)}}function A(e){return e}function W(e){let r={};e.resources&&(r.resources={}),e.tools&&(r.tools={});let o=new S({name:e.name,title:e.title,version:e.version},{capabilities:r,instructions:e.instructions});async function a(){if(!e.resources)throw new Error("resources not available");return typeof e.resources=="function"?await e.resources():e.resources}async function m(){if(!e.tools)throw new Error("tools not available");return typeof e.tools=="function"?await e.tools():e.tools}return o.oninitialized=async()=>{let s=o.getClientVersion(),t=o.getClientCapabilities();if(!s)throw new Error("client info not available after initialization");if(!t)throw new Error("client capabilities not available after initialization");let n={clientInfo:s,clientCapabilities:t};await e.onInitialize?.(n)},e.resources&&(o.setRequestHandler(C,async()=>({resources:(await a()).filter(t=>"uri"in t).map(({uri:t,name:n,description:l,mimeType:i})=>({uri:t,name:n,description:l,mimeType:i}))})),o.setRequestHandler(U,async()=>({resourceTemplates:(await a()).filter(t=>"uriTemplate"in t).map(({uriTemplate:t,name:n,description:l,mimeType:i})=>({uriTemplate:t,name:n,description:l,mimeType:i}))})),o.setRequestHandler(v,async s=>{try{let t=await a(),{uri:n}=s.params,i=t.filter(c=>"uri"in c).find(c=>T(c.uri,n));if(i){let c=await i.read(n);return{contents:Array.isArray(c)?c:[c]}}let u=t.filter(c=>"uriTemplate"in c),R=u.map(({uriTemplate:c})=>g(c)),f=h(n,R);if(!f)throw new Error("resource not found");let y=u.find(c=>c.uriTemplate===f.uri);if(!y)throw new Error("resource not found");let p=await y.read(n,f.params);return{contents:Array.isArray(p)?p:[p]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:x(t)})}]}}})),e.tools&&(o.setRequestHandler(P,async()=>{let s=await m();return{tools:await Promise.all(Object.entries(s).map(async([t,{description:n,annotations:l,parameters:i}])=>{let u=E.toJSONSchema(i,{target:"draft-7"});return{name:t,description:typeof n=="function"?await n():n,annotations:l,inputSchema:u}}))}}),o.setRequestHandler(b,async s=>{try{let t=await m(),n=s.params.name;if(!(n in t))throw new Error("tool not found");let l=t[n];if(!l)throw new Error("tool not found");let i=l.parameters.strict().parse(s.params.arguments??{}),R=await(async y=>{let p=await y.execute(i).then(d=>({success:!0,data:d})).catch(d=>({success:!1,error:d}));try{e.onToolCall?.({name:n,arguments:i,annotations:y.annotations,...p})}catch(d){console.error("Failed to run tool callback",d)}if(!p.success)throw p.error;return p.data})(l);return{content:R!=null?[{type:"text",text:JSON.stringify(R)}]:[]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:x(t)})}]}}})),o}function x(e){if(!e||typeof e!="object")return e;let r={},o=["name","message"];for(let a of o)a in e&&(r[a]=e[a]);return r}var w=class{#e;#t;ready;readable;writable;onclose;onerror;onmessage;constructor(){let r,o,a=new Promise(s=>{r=s}),m=new Promise(s=>{o=s});this.ready=Promise.all([a,m]).then(()=>{}),this.readable=new ReadableStream({start:s=>{this.#e=s,r()}}),this.writable=new WritableStream({start:s=>{this.#t=s,o()},write:s=>{this.onmessage?.(s)}})}async start(){await this.ready}async send(r){if(!this.#e)throw new Error("readable stream not initialized");this.#e.enqueue(r)}async close(){this.#e?.error(new Error("connection closed")),this.#t?.error(new Error("connection closed")),this.onclose?.()}};export{w as StreamTransport,W as createMcpServer,q as jsonResource,J as jsonResourceResponse,I as jsonResourceTemplate,L as resource,z as resourceTemplate,M as resources,A as tool};
1
+ import{Server as S}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as b,ListResourcesRequestSchema as C,ListResourceTemplatesRequestSchema as U,ListToolsRequestSchema as P,ReadResourceRequestSchema as v}from"@modelcontextprotocol/sdk/types.js";import{z as E}from"zod/v4";function g(e){try{return new URL(e),e}catch{throw new Error(`invalid uri: ${e}`)}}function T(e,r){let o=new URL(e),a=new URL(r);return o.href===a.href}function h(e,r){let a=new URL(e).pathname.split("/").slice(1);for(let m of r){let s=new URL(m),t=decodeURIComponent(s.pathname).split("/").slice(1);if(a.length!==t.length)continue;let n={},l=!0;for(let i=0;i<a.length;i++){let u=t[i],R=a[i];if(!u||!R)break;if(u.startsWith("{")&&u.endsWith("}")){let d=u.slice(1,-1);if(!d)break;n[d]=R}else if(a[i]!==t[i]){l=!1;break}}if(l)return{uri:m,params:n}}}function L(e,r){return{uri:e,...r}}function z(e,r){return{uriTemplate:e,...r}}function q(e,r){return{uri:e,mimeType:"application/json",...r}}function I(e,r){return{uriTemplate:e,mimeType:"application/json",...r}}function M(e,r){return r.map(o=>{if("uri"in o){let s=new URL(o.uri,`${e}://`),t=decodeURI(s.href);return{...o,uri:t}}let a=new URL(o.uriTemplate,`${e}://`),m=decodeURI(a.href);return{...o,uriTemplate:m}})}function J(e,r){return{uri:e,mimeType:"application/json",text:JSON.stringify(r)}}function A(e){return e}function W(e){let r={};e.resources&&(r.resources={}),e.tools&&(r.tools={});let o=new S({name:e.name,title:e.title,version:e.version},{capabilities:r,instructions:e.instructions});async function a(){if(!e.resources)throw new Error("resources not available");return typeof e.resources=="function"?await e.resources():e.resources}async function m(){if(!e.tools)throw new Error("tools not available");return typeof e.tools=="function"?await e.tools():e.tools}return o.oninitialized=async()=>{let s=o.getClientVersion(),t=o.getClientCapabilities();if(!s)throw new Error("client info not available after initialization");if(!t)throw new Error("client capabilities not available after initialization");let n={clientInfo:s,clientCapabilities:t};await e.onInitialize?.(n)},e.resources&&(o.setRequestHandler(C,async()=>({resources:(await a()).filter(t=>"uri"in t).map(({uri:t,name:n,description:l,mimeType:i})=>({uri:t,name:n,description:l,mimeType:i}))})),o.setRequestHandler(U,async()=>({resourceTemplates:(await a()).filter(t=>"uriTemplate"in t).map(({uriTemplate:t,name:n,description:l,mimeType:i})=>({uriTemplate:t,name:n,description:l,mimeType:i}))})),o.setRequestHandler(v,async s=>{try{let t=await a(),{uri:n}=s.params,i=t.filter(c=>"uri"in c).find(c=>T(c.uri,n));if(i){let c=await i.read(n);return{contents:Array.isArray(c)?c:[c]}}let u=t.filter(c=>"uriTemplate"in c),R=u.map(({uriTemplate:c})=>g(c)),d=h(n,R);if(!d)throw new Error("resource not found");let y=u.find(c=>c.uriTemplate===d.uri);if(!y)throw new Error("resource not found");let p=await y.read(n,d.params);return{contents:Array.isArray(p)?p:[p]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:x(t)})}]}}})),e.tools&&(o.setRequestHandler(P,async()=>{let s=await m();return{tools:await Promise.all(Object.entries(s).filter(([,t])=>!t.hidden).map(async([t,{description:n,annotations:l,parameters:i}])=>{let u=E.toJSONSchema(i,{target:"draft-7"});return{name:t,description:typeof n=="function"?await n():n,annotations:l,inputSchema:u}}))}}),o.setRequestHandler(b,async s=>{try{let t=await m(),n=s.params.name;if(!(n in t))throw new Error("tool not found");let l=t[n];if(!l)throw new Error("tool not found");let i=l.parameters.strict().parse(s.params.arguments??{}),R=await(async y=>{let p=await y.execute(i).then(f=>({success:!0,data:f})).catch(f=>({success:!1,error:f}));try{e.onToolCall?.({name:n,arguments:i,annotations:y.annotations,...p})}catch(f){console.error("Failed to run tool callback",f)}if(!p.success)throw p.error;return p.data})(l);return{content:R!=null?[{type:"text",text:JSON.stringify(R)}]:[]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:x(t)})}]}}})),o}function x(e){if(!e||typeof e!="object")return e;let r={},o=["name","message"];for(let a of o)a in e&&(r[a]=e[a]);return r}var w=class{#e;#t;ready;readable;writable;onclose;onerror;onmessage;constructor(){let r,o,a=new Promise(s=>{r=s}),m=new Promise(s=>{o=s});this.ready=Promise.all([a,m]).then(()=>{}),this.readable=new ReadableStream({start:s=>{this.#e=s,r()}}),this.writable=new WritableStream({start:s=>{this.#t=s,o()},write:s=>{this.onmessage?.(s)}})}async start(){await this.ready}async send(r){if(!this.#e)throw new Error("readable stream not initialized");this.#e.enqueue(r)}async close(){this.#e?.error(new Error("connection closed")),this.#t?.error(new Error("connection closed")),this.onclose?.()}};export{w as StreamTransport,W as createMcpServer,q as jsonResource,J as jsonResourceResponse,I as jsonResourceTemplate,L as resource,z as resourceTemplate,M as resources,A as tool};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts","../src/util.ts","../src/stream-transport.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport {\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n ReadResourceRequestSchema,\n type ClientCapabilities,\n type Implementation,\n type ListResourcesResult,\n type ListResourceTemplatesResult,\n type ReadResourceResult,\n type ServerCapabilities,\n type ListToolsResult,\n type Tool as McpTool,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod/v4';\nimport type {\n ExpandRecursively,\n ExtractNotification,\n ExtractParams,\n ExtractRequest,\n ExtractResult,\n} 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 execute(params: z.infer<Params>): Promise<z.infer<OutputSchema>>;\n};\n\n/**\n * Helper function to define an MCP resource while preserving type information.\n */\nexport function resource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri'>\n): Resource<Uri, Result> {\n return {\n uri,\n ...resource,\n };\n}\n\n/**\n * Helper function to define an MCP resource with a URI template while preserving type information.\n */\nexport function resourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource while preserving type information.\n */\nexport function jsonResource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>\n): Resource<Uri, Result> {\n return {\n uri,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource with a URI template while preserving type information.\n */\nexport function jsonResourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a list of resources that share a common URI scheme.\n */\nexport function resources<Scheme extends string>(\n scheme: Scheme,\n resources: (Resource | ResourceTemplate)[]\n): (\n | Resource<`${Scheme}://${string}`>\n | ResourceTemplate<`${Scheme}://${string}`>\n)[] {\n return resources.map((resource) => {\n if ('uri' in resource) {\n const url = new URL(resource.uri, `${scheme}://`);\n const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`;\n\n return {\n ...resource,\n uri,\n };\n }\n\n const url = new URL(resource.uriTemplate, `${scheme}://`);\n const uriTemplate = decodeURI(\n url.href\n ) as `${Scheme}://${typeof resource.uriTemplate}`;\n\n return {\n ...resource,\n uriTemplate,\n };\n });\n}\n\n/**\n * Helper function to create a JSON resource response.\n */\nexport function jsonResourceResponse<Uri extends string, Response>(\n uri: Uri,\n response: Response\n) {\n return {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(response),\n };\n}\n\n/**\n * Helper function to define an MCP tool while preserving type information.\n */\nexport function tool<\n Params extends z.ZodObject<any>,\n OutputSchema extends z.ZodObject<any>,\n>(tool: Tool<Params, OutputSchema>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n name: string;\n arguments: Record<string, unknown>;\n annotations?: Annotations;\n};\n\ntype ToolCallSuccessDetails = ToolCallBaseDetails & {\n success: true;\n data: unknown;\n};\n\ntype ToolCallErrorDetails = ToolCallBaseDetails & {\n success: false;\n error: unknown;\n};\n\nexport type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;\n\nexport type InitCallback = (initData: InitData) => void | Promise<void>;\nexport type ToolCallCallback = (details: ToolCallDetails) => void;\nexport type PropCallback<T> = () => T | Promise<T>;\nexport type Prop<T> = T | PropCallback<T>;\n\nexport type McpServerOptions = {\n /**\n * The name of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n name: string;\n\n /**\n * The title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Optional instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions?: string;\n\n /**\n * Callback for after a tool is called.\n */\n onToolCall?: ToolCallCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?: Prop<Record<string, Tool>>;\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer(options: McpServerOptions) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n instructions: options.instructions,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools() {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools()\n : options.tools;\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n ListResourcesRequestSchema,\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 ListResourceTemplatesRequestSchema,\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 ReadResourceRequestSchema,\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 ListToolsRequestSchema,\n async (): Promise<ListToolsResult> => {\n const tools = await getTools();\n\n return {\n tools: await Promise.all(\n Object.entries(tools).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(CallToolRequestSchema, async (request) => {\n try {\n const tools = await getTools();\n const toolName = request.params.name;\n\n if (!(toolName in tools)) {\n throw new Error('tool not found');\n }\n\n const tool = tools[toolName];\n\n if (!tool) {\n throw new Error('tool not found');\n }\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const executeWithCallback = async (tool: Tool) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n try {\n options.onToolCall?.({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\n });\n } catch (error) {\n // Don't fail the tool call if the callback fails\n console.error('Failed to run tool callback', error);\n }\n\n // Unwrap result\n if (!res.success) {\n throw res.error;\n }\n return res.data;\n };\n\n const result = await executeWithCallback(tool);\n\n const content =\n result != null\n ? [{ type: 'text', 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 // Expand types recursively for better intellisense\n type Request = ExpandRecursively<ExtractRequest<typeof server>>;\n type Notification = ExpandRecursively<ExtractNotification<typeof server>>;\n type Result = ExpandRecursively<ExtractResult<typeof server>>;\n\n return server as Server<Request, Notification, Result>;\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 { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';\nimport type { DuplexStream } from './types.js';\n\n/**\n * An MCP transport built on top of a duplex stream.\n * It uses a `ReadableStream` to receive messages and a `WritableStream` to send messages.\n *\n * Useful if you wish to pipe messages over your own stream-based transport or directly between two streams.\n */\nexport class StreamTransport\n implements Transport, DuplexStream<JSONRPCMessage>\n{\n #readableStreamController?: ReadableStreamDefaultController<JSONRPCMessage>;\n #writeableStreamController?: WritableStreamDefaultController;\n\n ready: Promise<void>;\n\n readable: ReadableStream<JSONRPCMessage>;\n writable: WritableStream<JSONRPCMessage>;\n\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n\n constructor() {\n let resolveReadReady: () => void;\n let resolveWriteReady: () => void;\n\n const readReady = new Promise<void>((resolve) => {\n resolveReadReady = resolve;\n });\n\n const writeReady = new Promise<void>((resolve) => {\n resolveWriteReady = resolve;\n });\n\n this.ready = Promise.all([readReady, writeReady]).then(() => {});\n\n this.readable = new ReadableStream({\n start: (controller) => {\n this.#readableStreamController = controller;\n resolveReadReady();\n },\n });\n\n this.writable = new WritableStream({\n start: (controller) => {\n this.#writeableStreamController = controller;\n resolveWriteReady();\n },\n write: (message) => {\n this.onmessage?.(message);\n },\n });\n }\n\n async start() {\n await this.ready;\n }\n\n async send(message: JSONRPCMessage) {\n if (!this.#readableStreamController) {\n throw new Error('readable stream not initialized');\n }\n this.#readableStreamController.enqueue(message);\n }\n\n async close() {\n this.#readableStreamController?.error(new Error('connection closed'));\n this.#writeableStreamController?.error(new Error('connection closed'));\n this.onclose?.();\n }\n}\n"],"mappings":"AAAA,OAAS,UAAAA,MAAc,4CACvB,OACE,yBAAAC,EACA,8BAAAC,EACA,sCAAAC,EACA,0BAAAC,EACA,6BAAAC,MASK,qCACP,OAAS,KAAAC,MAAS,SCXX,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,EADM,IAAI,IAAIR,CAAG,EACF,SAAS,MAAM,GAAG,EAAE,MAAM,CAAC,EAEhD,QAAWS,KAAeF,EAAc,CACtC,IAAMG,EAAc,IAAI,IAAID,CAAW,EACjCE,EAAmB,mBAAmBD,EAAY,QAAQ,EAC7D,MAAM,GAAG,EACT,MAAM,CAAC,EAEV,GAAIF,EAAS,SAAWG,EAAiB,OACvC,SAGF,IAAMC,EAAiC,CAAC,EACpCC,EAAU,GAEd,QAAS,EAAI,EAAG,EAAIL,EAAS,OAAQ,IAAK,CACxC,IAAMM,EAAkBH,EAAiB,CAAC,EACpCI,EAAUP,EAAS,CAAC,EAE1B,GAAI,CAACM,GAAmB,CAACC,EACvB,MAGF,GAAID,EAAgB,WAAW,GAAG,GAAKA,EAAgB,SAAS,GAAG,EAAG,CACpE,IAAME,EAAWF,EAAgB,MAAM,EAAG,EAAE,EAE5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","names":["Server","CallToolRequestSchema","ListResourcesRequestSchema","ListResourceTemplatesRequestSchema","ListToolsRequestSchema","ReadResourceRequestSchema","z","assertValidUri","uri","compareUris","uriA","uriB","urlA","urlB","matchUriTemplate","uriTemplates","segments","resourceUri","resourceUrl","resourceSegments","params","isMatch","resourceSegment","segment","paramKey","resource","uri","resourceTemplate","uriTemplate","jsonResource","jsonResourceTemplate","resources","scheme","url","jsonResourceResponse","response","tool","createMcpServer","options","capabilities","server","Server","getResources","getTools","clientInfo","clientCapabilities","initData","ListResourcesRequestSchema","name","description","mimeType","ListResourceTemplatesRequestSchema","ReadResourceRequestSchema","request","allResources","compareUris","result","resourceTemplates","resourceTemplateUris","assertValidUri","templateMatch","matchUriTemplate","r","error","enumerateError","ListToolsRequestSchema","tools","annotations","parameters","inputSchema","z","CallToolRequestSchema","toolName","args","res","data","newError","errorProps","prop","StreamTransport","#readableStreamController","#writeableStreamController","resolveReadReady","resolveWriteReady","readReady","resolve","writeReady","controller","message"]}
1
+ {"version":3,"sources":["../src/server.ts","../src/util.ts","../src/stream-transport.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport {\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n ReadResourceRequestSchema,\n type ClientCapabilities,\n type Implementation,\n type ListResourcesResult,\n type ListResourceTemplatesResult,\n type ReadResourceResult,\n type ServerCapabilities,\n type ListToolsResult,\n type Tool as McpTool,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod/v4';\nimport type {\n ExpandRecursively,\n ExtractNotification,\n ExtractParams,\n ExtractRequest,\n ExtractResult,\n} from './types.js';\nimport { assertValidUri, compareUris, matchUriTemplate } from './util.js';\n\nexport type Scheme = string;\nexport type Annotations = NonNullable<\n ListToolsResult['tools'][number]['annotations']\n>;\n\nexport type Resource<Uri extends string = string, Result = unknown> = {\n uri: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(uri: `${Scheme}://${Uri}`): Promise<Result>;\n};\n\nexport type ResourceTemplate<Uri extends string = string, Result = unknown> = {\n uriTemplate: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(\n uri: `${Scheme}://${Uri}`,\n params: {\n [Param in ExtractParams<Uri>]: string;\n }\n ): Promise<Result>;\n};\n\nexport type Tool<\n Params extends z.ZodObject<any> = z.ZodObject<any>,\n // MCP spec restricts outputSchema to type \"object\" at the root level:\n // https://modelcontextprotocol.io/specification/2025-11-25/schema#tool-outputschema\n OutputSchema extends z.ZodObject<any> = z.ZodObject<any>,\n> = {\n description: Prop<string>;\n annotations?: Annotations;\n parameters: Params;\n outputSchema: OutputSchema;\n /** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */\n hidden?: boolean;\n execute(params: z.infer<Params>): Promise<z.infer<OutputSchema>>;\n};\n\n/**\n * Helper function to define an MCP resource while preserving type information.\n */\nexport function resource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri'>\n): Resource<Uri, Result> {\n return {\n uri,\n ...resource,\n };\n}\n\n/**\n * Helper function to define an MCP resource with a URI template while preserving type information.\n */\nexport function resourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource while preserving type information.\n */\nexport function jsonResource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>\n): Resource<Uri, Result> {\n return {\n uri,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource with a URI template while preserving type information.\n */\nexport function jsonResourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a list of resources that share a common URI scheme.\n */\nexport function resources<Scheme extends string>(\n scheme: Scheme,\n resources: (Resource | ResourceTemplate)[]\n): (\n | Resource<`${Scheme}://${string}`>\n | ResourceTemplate<`${Scheme}://${string}`>\n)[] {\n return resources.map((resource) => {\n if ('uri' in resource) {\n const url = new URL(resource.uri, `${scheme}://`);\n const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`;\n\n return {\n ...resource,\n uri,\n };\n }\n\n const url = new URL(resource.uriTemplate, `${scheme}://`);\n const uriTemplate = decodeURI(\n url.href\n ) as `${Scheme}://${typeof resource.uriTemplate}`;\n\n return {\n ...resource,\n uriTemplate,\n };\n });\n}\n\n/**\n * Helper function to create a JSON resource response.\n */\nexport function jsonResourceResponse<Uri extends string, Response>(\n uri: Uri,\n response: Response\n) {\n return {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(response),\n };\n}\n\n/**\n * Helper function to define an MCP tool while preserving type information.\n */\nexport function tool<\n Params extends z.ZodObject<any>,\n OutputSchema extends z.ZodObject<any>,\n>(tool: Tool<Params, OutputSchema>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n name: string;\n arguments: Record<string, unknown>;\n annotations?: Annotations;\n};\n\ntype ToolCallSuccessDetails = ToolCallBaseDetails & {\n success: true;\n data: unknown;\n};\n\ntype ToolCallErrorDetails = ToolCallBaseDetails & {\n success: false;\n error: unknown;\n};\n\nexport type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;\n\nexport type InitCallback = (initData: InitData) => void | Promise<void>;\nexport type ToolCallCallback = (details: ToolCallDetails) => void;\nexport type PropCallback<T> = () => T | Promise<T>;\nexport type Prop<T> = T | PropCallback<T>;\n\nexport type McpServerOptions = {\n /**\n * The name of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n name: string;\n\n /**\n * The title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Optional instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions?: string;\n\n /**\n * Callback for after a tool is called.\n */\n onToolCall?: ToolCallCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?: Prop<Record<string, Tool>>;\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer(options: McpServerOptions) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n instructions: options.instructions,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools() {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools()\n : options.tools;\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n ListResourcesRequestSchema,\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 ListResourceTemplatesRequestSchema,\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 ReadResourceRequestSchema,\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 ListToolsRequestSchema,\n async (): Promise<ListToolsResult> => {\n const tools = await getTools();\n\n return {\n tools: await Promise.all(\n Object.entries(tools)\n .filter(([, tool]) => !tool.hidden)\n .map(async ([name, { description, annotations, parameters }]) => {\n const inputSchema = z.toJSONSchema(parameters, {\n target: 'draft-7',\n });\n\n return {\n name,\n description:\n typeof description === 'function'\n ? await description()\n : description,\n annotations,\n // Casting the same as the SDK does:\n // https://github.com/modelcontextprotocol/typescript-sdk/blob/fb07af810b51003c338dc4885a9e42f54519f9af/src/server/mcp.ts#L154\n inputSchema: inputSchema as McpTool['inputSchema'],\n };\n })\n ),\n } satisfies ListToolsResult;\n }\n );\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n try {\n const tools = await getTools();\n const toolName = request.params.name;\n\n if (!(toolName in tools)) {\n throw new Error('tool not found');\n }\n\n const tool = tools[toolName];\n\n if (!tool) {\n throw new Error('tool not found');\n }\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const executeWithCallback = async (tool: Tool) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n try {\n options.onToolCall?.({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\n });\n } catch (error) {\n // Don't fail the tool call if the callback fails\n console.error('Failed to run tool callback', error);\n }\n\n // Unwrap result\n if (!res.success) {\n throw res.error;\n }\n return res.data;\n };\n\n const result = await executeWithCallback(tool);\n\n const content =\n result != null\n ? [{ type: 'text', 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 // Expand types recursively for better intellisense\n type Request = ExpandRecursively<ExtractRequest<typeof server>>;\n type Notification = ExpandRecursively<ExtractNotification<typeof server>>;\n type Result = ExpandRecursively<ExtractResult<typeof server>>;\n\n return server as Server<Request, Notification, Result>;\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 { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';\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 }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AACA,GAID,OAAOA,GAAU,SACnB,OAAOA,EAGT,IAAMa,EAAoC,CAAC,EAErCC,EAAa,CAAC,OAAQ,SAAS,EAErC,QAAWC,KAAQD,EACbC,KAAQf,IACVa,EAASE,CAAI,EAAKf,EAAkCe,CAAI,GAI5D,OAAOF,CACT,CEvjBO,IAAMG,EAAN,KAEP,CACEC,GACAC,GAEA,MAEA,SACA,SAEA,QACA,QACA,UAEA,aAAc,CACZ,IAAIC,EACAC,EAEEC,EAAY,IAAI,QAAeC,GAAY,CAC/CH,EAAmBG,CACrB,CAAC,EAEKC,EAAa,IAAI,QAAeD,GAAY,CAChDF,EAAoBE,CACtB,CAAC,EAED,KAAK,MAAQ,QAAQ,IAAI,CAACD,EAAWE,CAAU,CAAC,EAAE,KAAK,IAAM,CAAC,CAAC,EAE/D,KAAK,SAAW,IAAI,eAAe,CACjC,MAAQC,GAAe,CACrB,KAAKP,GAA4BO,EACjCL,EAAiB,CACnB,CACF,CAAC,EAED,KAAK,SAAW,IAAI,eAAe,CACjC,MAAQK,GAAe,CACrB,KAAKN,GAA6BM,EAClCJ,EAAkB,CACpB,EACA,MAAQK,GAAY,CAClB,KAAK,YAAYA,CAAO,CAC1B,CACF,CAAC,CACH,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,KACb,CAEA,MAAM,KAAKA,EAAyB,CAClC,GAAI,CAAC,KAAKR,GACR,MAAM,IAAI,MAAM,iCAAiC,EAEnD,KAAKA,GAA0B,QAAQQ,CAAO,CAChD,CAEA,MAAM,OAAQ,CACZ,KAAKR,IAA2B,MAAM,IAAI,MAAM,mBAAmB,CAAC,EACpE,KAAKC,IAA4B,MAAM,IAAI,MAAM,mBAAmB,CAAC,EACrE,KAAK,UAAU,CACjB,CACF","names":["Server","CallToolRequestSchema","ListResourcesRequestSchema","ListResourceTemplatesRequestSchema","ListToolsRequestSchema","ReadResourceRequestSchema","z","assertValidUri","uri","compareUris","uriA","uriB","urlA","urlB","matchUriTemplate","uriTemplates","segments","resourceUri","resourceUrl","resourceSegments","params","isMatch","resourceSegment","segment","paramKey","resource","uri","resourceTemplate","uriTemplate","jsonResource","jsonResourceTemplate","resources","scheme","url","jsonResourceResponse","response","tool","createMcpServer","options","capabilities","server","Server","getResources","getTools","clientInfo","clientCapabilities","initData","ListResourcesRequestSchema","name","description","mimeType","ListResourceTemplatesRequestSchema","ReadResourceRequestSchema","request","allResources","compareUris","result","resourceTemplates","resourceTemplateUris","assertValidUri","templateMatch","matchUriTemplate","r","error","enumerateError","ListToolsRequestSchema","tools","annotations","parameters","inputSchema","z","CallToolRequestSchema","toolName","args","res","data","newError","errorProps","prop","StreamTransport","#readableStreamController","#writeableStreamController","resolveReadReady","resolveWriteReady","readReady","resolve","writeReady","controller","message"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supabase/mcp-utils",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "MCP utilities",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {