@supabase/mcp-utils 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -13
- package/dist/index.d.ts +6 -13
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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');
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _zodtojsonschema = require('zod-to-json-schema'); var _zodtojsonschema2 = _interopRequireDefault(_zodtojsonschema);function y(e){try{return new URL(e),e}catch (e2){throw new Error(`invalid uri: ${e}`)}}function g(e,r){let o=new URL(e),n=new URL(r);return o.href===n.href}function x(e,r){let n=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(n.length!==t.length)continue;let i={},c=!0;for(let a=0;a<n.length;a++){let u=t[a],R=n[a];if(!u||!R)break;if(u.startsWith("{")&&u.endsWith("}")){let p=u.slice(1,-1);if(!p)break;i[p]=R}else if(n[a]!==t[a]){c=!1;break}}if(c)return{uri:m,params:i}}}function I(e,r){return{uri:e,...r}}function L(e,r){return{uriTemplate:e,...r}}function z(e,r){return{uri:e,mimeType:"application/json",...r}}function J(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 n=new URL(o.uriTemplate,`${e}://`),m=decodeURI(n.href);return{...o,uriTemplate:m}})}function D(e,r){return{uri:e,mimeType:"application/json",text:JSON.stringify(r)}}function W(e){return e}function A(e){let r={};e.resources&&(r.resources={}),e.tools&&(r.tools={});let o=new (0, _indexjs.Server)({name:e.name,version:e.version},{capabilities:r});async function n(){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 i={clientInfo:s,clientCapabilities:t};await _optionalChain([e, 'access', _ => _.onInitialize, 'optionalCall', _2 => _2(i)])},e.resources&&(o.setRequestHandler(_typesjs.ListResourcesRequestSchema,async()=>({resources:(await n()).filter(t=>"uri"in t).map(({uri:t,name:i,description:c,mimeType:a})=>({uri:t,name:i,description:c,mimeType:a}))})),o.setRequestHandler(_typesjs.ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:(await n()).filter(t=>"uriTemplate"in t).map(({uriTemplate:t,name:i,description:c,mimeType:a})=>({uriTemplate:t,name:i,description:c,mimeType:a}))})),o.setRequestHandler(_typesjs.ReadResourceRequestSchema,async s=>{try{let t=await n(),{uri:i}=s.params,a=t.filter(l=>"uri"in l).find(l=>g(l.uri,i));if(a){let l=await a.read(i);return{contents:Array.isArray(l)?l:[l]}}let u=t.filter(l=>"uriTemplate"in l),R=u.map(({uriTemplate:l})=>y(l)),p=x(i,R);if(!p)throw new Error("resource not found");let d=u.find(l=>l.uriTemplate===p.uri);if(!d)throw new Error("resource not found");let f=await d.read(i,p.params);return{contents:Array.isArray(f)?f:[f]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:w(t)})}]}}})),e.tools&&(o.setRequestHandler(_typesjs.ListToolsRequestSchema,async()=>{let s=await m();return{tools:Object.entries(s).map(([t,{description:i,parameters:c}])=>({name:t,description:i,inputSchema:_zodtojsonschema2.default.call(void 0, c)}))}}),o.setRequestHandler(_typesjs.CallToolRequestSchema,async s=>{try{let t=await m(),i=s.params.name;if(!(i in t))throw new Error("tool not found");let c=t[i];if(!c)throw new Error("tool not found");let a=c.parameters.strict().parse(_nullishCoalesce(s.params.arguments, () => ({}))),u=await c.execute(a);return{content:u?[{type:"text",text:JSON.stringify(u)}]:[]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:w(t)})}]}}})),o}function w(e){if(!e||typeof e!="object")return e;let r={},o=["name","message"];for(let n of o)n in e&&(r[n]=e[n]);return r}var h=class{#e;#t;constructor(){let r,o,n=new Promise(s=>{r=s}),m=new Promise(s=>{o=s});this.ready=Promise.all([n,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', _3 => _3.onmessage, 'optionalCall', _4 => _4(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', _5 => _5.#e, 'optionalAccess', _6 => _6.error, 'call', _7 => _7(new Error("connection closed"))]),_optionalChain([this, 'access', _8 => _8.#t, 'optionalAccess', _9 => _9.error, 'call', _10 => _10(new Error("connection closed"))]),_optionalChain([this, 'access', _11 => _11.onclose, 'optionalCall', _12 => _12()])}};exports.StreamTransport = h; exports.createMcpServer = A; exports.jsonResource = z; exports.jsonResourceResponse = D; exports.jsonResourceTemplate = J; exports.resource = I; exports.resourceTemplate = L; exports.resources = M; exports.tool = W;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/util.ts"],"names":["assertValidUri","uri"],"mappings":"AAAA,q1BAAuB,6DAYhB,eACW,uHACU,SCTZA,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/grichardson/Documents/dev/supabase/mcp-server-supabase/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 ServerCapabilities,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\nimport zodToJsonSchema from 'zod-to-json-schema';\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;\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 Result = unknown,\n> = {\n description: string;\n parameters: Params;\n execute(params: z.infer<Params>): Promise<Result>;\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<Params extends z.ZodObject<any>, Result>(\n tool: Tool<Params, Result>\n) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\nexport type PropCallback<T> = (initData: InitData) => 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 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 * This is guaranteed to run before any primitives like resources or tools\n * are served. If a promise is returned from this callback, the server will\n * wait for it to resolve before serving other primitives. This is useful for\n * initializing things like API connections or other async tasks that might\n * depend on client information before serving other primitives.\n */\n onInitialize?: PropCallback<void>;\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. The function will\n * also pass the client information and capabilities as context.\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. The function will also pass\n * the client information and capabilities as context.\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 version: options.version,\n },\n {\n capabilities,\n }\n );\n\n let resolveInitialized: (initData: InitData) => void;\n const initialized = new Promise<InitData>((resolve) => {\n resolveInitialized = resolve;\n });\n\n async function getResources() {\n const initData = await initialized;\n\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources(initData)\n : options.resources;\n }\n\n async function getTools() {\n const initData = await initialized;\n\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools(initData)\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 resolveInitialized(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(ReadResourceRequestSchema, async (request) => {\n try {\n const allResources = await getResources();\n const { uri } = request.params;\n\n const resources = allResources.filter((resource) => 'uri' in resource);\n const resource = resources.find((resource) =>\n compareUris(resource.uri, uri)\n );\n\n if (resource) {\n return await resource.read(uri as `${string}://${string}`);\n }\n\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceTemplateUris = resourceTemplates.map(({ uriTemplate }) =>\n 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 } as any;\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 if (options.tools) {\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n const tools = await getTools();\n return {\n tools: Object.entries(tools).map(\n ([name, { description, parameters }]) => {\n return {\n name,\n description,\n inputSchema: zodToJsonSchema(parameters),\n };\n }\n ),\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\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const result = await tool.execute(args);\n const content = result\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,q1BAAuB,6DAahB,uHAEqB,SCVZA,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/grichardson/Documents/dev/supabase/mcp-server-supabase/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} from '@modelcontextprotocol/sdk/types.js';\nimport type { z } from 'zod';\nimport zodToJsonSchema from 'zod-to-json-schema';\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;\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 Result = unknown,\n> = {\n description: string;\n parameters: Params;\n execute(params: z.infer<Params>): Promise<Result>;\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<Params extends z.ZodObject<any>, Result>(\n tool: Tool<Params, Result>\n) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\nexport type InitCallback = (initData: InitData) => void | Promise<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 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 * 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 version: options.version,\n },\n {\n capabilities,\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(ListToolsRequestSchema, async () => {\n const tools = await getTools();\n return {\n tools: Object.entries(tools).map(\n ([name, { description, parameters }]) => {\n return {\n name,\n description,\n inputSchema: zodToJsonSchema(parameters),\n };\n }\n ),\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\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const result = await tool.execute(args);\n const content = result\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
|
@@ -97,7 +97,8 @@ type InitData = {
|
|
|
97
97
|
clientInfo: Implementation;
|
|
98
98
|
clientCapabilities: ClientCapabilities;
|
|
99
99
|
};
|
|
100
|
-
type
|
|
100
|
+
type InitCallback = (initData: InitData) => void | Promise<void>;
|
|
101
|
+
type PropCallback<T> = () => T | Promise<T>;
|
|
101
102
|
type Prop<T> = T | PropCallback<T>;
|
|
102
103
|
type McpServerOptions = {
|
|
103
104
|
/**
|
|
@@ -112,14 +113,8 @@ type McpServerOptions = {
|
|
|
112
113
|
version: string;
|
|
113
114
|
/**
|
|
114
115
|
* Callback for when initialization has fully completed with the client.
|
|
115
|
-
*
|
|
116
|
-
* This is guaranteed to run before any primitives like resources or tools
|
|
117
|
-
* are served. If a promise is returned from this callback, the server will
|
|
118
|
-
* wait for it to resolve before serving other primitives. This is useful for
|
|
119
|
-
* initializing things like API connections or other async tasks that might
|
|
120
|
-
* depend on client information before serving other primitives.
|
|
121
116
|
*/
|
|
122
|
-
onInitialize?:
|
|
117
|
+
onInitialize?: InitCallback;
|
|
123
118
|
/**
|
|
124
119
|
* Resources to be served by the server. These can be defined as a static
|
|
125
120
|
* object or as a function that dynamically returns the object synchronously
|
|
@@ -127,8 +122,7 @@ type McpServerOptions = {
|
|
|
127
122
|
*
|
|
128
123
|
* If defined as a function, the function will be called whenever the client
|
|
129
124
|
* asks for the list of resources or reads a resource. This allows for dynamic
|
|
130
|
-
* resources that can change after the server has started.
|
|
131
|
-
* also pass the client information and capabilities as context.
|
|
125
|
+
* resources that can change after the server has started.
|
|
132
126
|
*/
|
|
133
127
|
resources?: Prop<(Resource<string, unknown> | ResourceTemplate<string, unknown>)[]>;
|
|
134
128
|
/**
|
|
@@ -138,8 +132,7 @@ type McpServerOptions = {
|
|
|
138
132
|
*
|
|
139
133
|
* If defined as a function, the function will be called whenever the client
|
|
140
134
|
* asks for the list of tools or invokes a tool. This allows for dynamic tools
|
|
141
|
-
* that can change after the server has started.
|
|
142
|
-
* the client information and capabilities as context.
|
|
135
|
+
* that can change after the server has started.
|
|
143
136
|
*/
|
|
144
137
|
tools?: Prop<Record<string, Tool>>;
|
|
145
138
|
};
|
|
@@ -193,4 +186,4 @@ declare class StreamTransport implements Transport, DuplexStream<JSONRPCMessage>
|
|
|
193
186
|
close(): Promise<void>;
|
|
194
187
|
}
|
|
195
188
|
|
|
196
|
-
export { type DuplexStream, type ExpandRecursively, type ExtractNotification, type ExtractParams, type ExtractRequest, type ExtractResult, type InitData, type McpServerOptions, type Prop, type PropCallback, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, createMcpServer, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
|
|
189
|
+
export { type DuplexStream, type ExpandRecursively, type ExtractNotification, type ExtractParams, type ExtractRequest, type ExtractResult, type InitCallback, type InitData, type McpServerOptions, type Prop, type PropCallback, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, createMcpServer, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
|
package/dist/index.d.ts
CHANGED
|
@@ -97,7 +97,8 @@ type InitData = {
|
|
|
97
97
|
clientInfo: Implementation;
|
|
98
98
|
clientCapabilities: ClientCapabilities;
|
|
99
99
|
};
|
|
100
|
-
type
|
|
100
|
+
type InitCallback = (initData: InitData) => void | Promise<void>;
|
|
101
|
+
type PropCallback<T> = () => T | Promise<T>;
|
|
101
102
|
type Prop<T> = T | PropCallback<T>;
|
|
102
103
|
type McpServerOptions = {
|
|
103
104
|
/**
|
|
@@ -112,14 +113,8 @@ type McpServerOptions = {
|
|
|
112
113
|
version: string;
|
|
113
114
|
/**
|
|
114
115
|
* Callback for when initialization has fully completed with the client.
|
|
115
|
-
*
|
|
116
|
-
* This is guaranteed to run before any primitives like resources or tools
|
|
117
|
-
* are served. If a promise is returned from this callback, the server will
|
|
118
|
-
* wait for it to resolve before serving other primitives. This is useful for
|
|
119
|
-
* initializing things like API connections or other async tasks that might
|
|
120
|
-
* depend on client information before serving other primitives.
|
|
121
116
|
*/
|
|
122
|
-
onInitialize?:
|
|
117
|
+
onInitialize?: InitCallback;
|
|
123
118
|
/**
|
|
124
119
|
* Resources to be served by the server. These can be defined as a static
|
|
125
120
|
* object or as a function that dynamically returns the object synchronously
|
|
@@ -127,8 +122,7 @@ type McpServerOptions = {
|
|
|
127
122
|
*
|
|
128
123
|
* If defined as a function, the function will be called whenever the client
|
|
129
124
|
* asks for the list of resources or reads a resource. This allows for dynamic
|
|
130
|
-
* resources that can change after the server has started.
|
|
131
|
-
* also pass the client information and capabilities as context.
|
|
125
|
+
* resources that can change after the server has started.
|
|
132
126
|
*/
|
|
133
127
|
resources?: Prop<(Resource<string, unknown> | ResourceTemplate<string, unknown>)[]>;
|
|
134
128
|
/**
|
|
@@ -138,8 +132,7 @@ type McpServerOptions = {
|
|
|
138
132
|
*
|
|
139
133
|
* If defined as a function, the function will be called whenever the client
|
|
140
134
|
* asks for the list of tools or invokes a tool. This allows for dynamic tools
|
|
141
|
-
* that can change after the server has started.
|
|
142
|
-
* the client information and capabilities as context.
|
|
135
|
+
* that can change after the server has started.
|
|
143
136
|
*/
|
|
144
137
|
tools?: Prop<Record<string, Tool>>;
|
|
145
138
|
};
|
|
@@ -193,4 +186,4 @@ declare class StreamTransport implements Transport, DuplexStream<JSONRPCMessage>
|
|
|
193
186
|
close(): Promise<void>;
|
|
194
187
|
}
|
|
195
188
|
|
|
196
|
-
export { type DuplexStream, type ExpandRecursively, type ExtractNotification, type ExtractParams, type ExtractRequest, type ExtractResult, type InitData, type McpServerOptions, type Prop, type PropCallback, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, createMcpServer, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
|
|
189
|
+
export { type DuplexStream, type ExpandRecursively, type ExtractNotification, type ExtractParams, type ExtractRequest, type ExtractResult, type InitCallback, type InitData, type McpServerOptions, type Prop, type PropCallback, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, createMcpServer, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Server as
|
|
1
|
+
import{Server as T}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as S,ListResourcesRequestSchema as U,ListResourceTemplatesRequestSchema as b,ListToolsRequestSchema as P,ReadResourceRequestSchema as v}from"@modelcontextprotocol/sdk/types.js";import E from"zod-to-json-schema";function y(e){try{return new URL(e),e}catch{throw new Error(`invalid uri: ${e}`)}}function g(e,r){let o=new URL(e),n=new URL(r);return o.href===n.href}function x(e,r){let n=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(n.length!==t.length)continue;let i={},c=!0;for(let a=0;a<n.length;a++){let u=t[a],R=n[a];if(!u||!R)break;if(u.startsWith("{")&&u.endsWith("}")){let p=u.slice(1,-1);if(!p)break;i[p]=R}else if(n[a]!==t[a]){c=!1;break}}if(c)return{uri:m,params:i}}}function I(e,r){return{uri:e,...r}}function L(e,r){return{uriTemplate:e,...r}}function z(e,r){return{uri:e,mimeType:"application/json",...r}}function J(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 n=new URL(o.uriTemplate,`${e}://`),m=decodeURI(n.href);return{...o,uriTemplate:m}})}function D(e,r){return{uri:e,mimeType:"application/json",text:JSON.stringify(r)}}function W(e){return e}function A(e){let r={};e.resources&&(r.resources={}),e.tools&&(r.tools={});let o=new T({name:e.name,version:e.version},{capabilities:r});async function n(){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 i={clientInfo:s,clientCapabilities:t};await e.onInitialize?.(i)},e.resources&&(o.setRequestHandler(U,async()=>({resources:(await n()).filter(t=>"uri"in t).map(({uri:t,name:i,description:c,mimeType:a})=>({uri:t,name:i,description:c,mimeType:a}))})),o.setRequestHandler(b,async()=>({resourceTemplates:(await n()).filter(t=>"uriTemplate"in t).map(({uriTemplate:t,name:i,description:c,mimeType:a})=>({uriTemplate:t,name:i,description:c,mimeType:a}))})),o.setRequestHandler(v,async s=>{try{let t=await n(),{uri:i}=s.params,a=t.filter(l=>"uri"in l).find(l=>g(l.uri,i));if(a){let l=await a.read(i);return{contents:Array.isArray(l)?l:[l]}}let u=t.filter(l=>"uriTemplate"in l),R=u.map(({uriTemplate:l})=>y(l)),p=x(i,R);if(!p)throw new Error("resource not found");let d=u.find(l=>l.uriTemplate===p.uri);if(!d)throw new Error("resource not found");let f=await d.read(i,p.params);return{contents:Array.isArray(f)?f:[f]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:w(t)})}]}}})),e.tools&&(o.setRequestHandler(P,async()=>{let s=await m();return{tools:Object.entries(s).map(([t,{description:i,parameters:c}])=>({name:t,description:i,inputSchema:E(c)}))}}),o.setRequestHandler(S,async s=>{try{let t=await m(),i=s.params.name;if(!(i in t))throw new Error("tool not found");let c=t[i];if(!c)throw new Error("tool not found");let a=c.parameters.strict().parse(s.params.arguments??{}),u=await c.execute(a);return{content:u?[{type:"text",text:JSON.stringify(u)}]:[]}}catch(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:w(t)})}]}}})),o}function w(e){if(!e||typeof e!="object")return e;let r={},o=["name","message"];for(let n of o)n in e&&(r[n]=e[n]);return r}var h=class{#e;#t;ready;readable;writable;onclose;onerror;onmessage;constructor(){let r,o,n=new Promise(s=>{r=s}),m=new Promise(s=>{o=s});this.ready=Promise.all([n,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{h as StreamTransport,A as createMcpServer,z as jsonResource,D as jsonResourceResponse,J as jsonResourceTemplate,I as resource,L as resourceTemplate,M as resources,W 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 ServerCapabilities,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\nimport zodToJsonSchema from 'zod-to-json-schema';\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;\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 Result = unknown,\n> = {\n description: string;\n parameters: Params;\n execute(params: z.infer<Params>): Promise<Result>;\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<Params extends z.ZodObject<any>, Result>(\n tool: Tool<Params, Result>\n) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\nexport type PropCallback<T> = (initData: InitData) => 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 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 * This is guaranteed to run before any primitives like resources or tools\n * are served. If a promise is returned from this callback, the server will\n * wait for it to resolve before serving other primitives. This is useful for\n * initializing things like API connections or other async tasks that might\n * depend on client information before serving other primitives.\n */\n onInitialize?: PropCallback<void>;\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. The function will\n * also pass the client information and capabilities as context.\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. The function will also pass\n * the client information and capabilities as context.\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 version: options.version,\n },\n {\n capabilities,\n }\n );\n\n let resolveInitialized: (initData: InitData) => void;\n const initialized = new Promise<InitData>((resolve) => {\n resolveInitialized = resolve;\n });\n\n async function getResources() {\n const initData = await initialized;\n\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources(initData)\n : options.resources;\n }\n\n async function getTools() {\n const initData = await initialized;\n\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools(initData)\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 resolveInitialized(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(ReadResourceRequestSchema, async (request) => {\n try {\n const allResources = await getResources();\n const { uri } = request.params;\n\n const resources = allResources.filter((resource) => 'uri' in resource);\n const resource = resources.find((resource) =>\n compareUris(resource.uri, uri)\n );\n\n if (resource) {\n return await resource.read(uri as `${string}://${string}`);\n }\n\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceTemplateUris = resourceTemplates.map(({ uriTemplate }) =>\n 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 } as any;\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 if (options.tools) {\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n const tools = await getTools();\n return {\n tools: Object.entries(tools).map(\n ([name, { description, parameters }]) => {\n return {\n name,\n description,\n inputSchema: zodToJsonSchema(parameters),\n };\n }\n ),\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\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const result = await tool.execute(args);\n const content = result\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,MAMK,qCACP,MAAkB,MAClB,OAAOC,M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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","zodToJsonSchema","assertValidUri","uri","compareUris","uriA","uriB","urlA","urlB","matchUriTemplate","uriTemplates","segments","resourceUri","resourceUrl","resourceSegments","params","isMatch","i","resourceSegment","segment","paramKey","resource","uri","resourceTemplate","uriTemplate","jsonResource","jsonResourceTemplate","resources","scheme","url","jsonResourceResponse","response","tool","createMcpServer","options","capabilities","server","Server","resolveInitialized","initialized","resolve","getResources","initData","getTools","clientInfo","clientCapabilities","ListResourcesRequestSchema","name","description","mimeType","ListResourceTemplatesRequestSchema","ReadResourceRequestSchema","request","allResources","compareUris","resourceTemplates","resourceTemplateUris","assertValidUri","templateMatch","matchUriTemplate","r","result","error","enumerateError","ListToolsRequestSchema","tools","parameters","zodToJsonSchema","CallToolRequestSchema","toolName","args","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} from '@modelcontextprotocol/sdk/types.js';\nimport type { z } from 'zod';\nimport zodToJsonSchema from 'zod-to-json-schema';\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;\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 Result = unknown,\n> = {\n description: string;\n parameters: Params;\n execute(params: z.infer<Params>): Promise<Result>;\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<Params extends z.ZodObject<any>, Result>(\n tool: Tool<Params, Result>\n) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\nexport type InitCallback = (initData: InitData) => void | Promise<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 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 * 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 version: options.version,\n },\n {\n capabilities,\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(ListToolsRequestSchema, async () => {\n const tools = await getTools();\n return {\n tools: Object.entries(tools).map(\n ([name, { description, parameters }]) => {\n return {\n name,\n description,\n inputSchema: zodToJsonSchema(parameters),\n };\n }\n ),\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\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const result = await tool.execute(args);\n const content = result\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,MAOK,qCAEP,OAAOC,MAAqB,qBCVrB,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,QAASC,EAAI,EAAGA,EAAIN,EAAS,OAAQM,IAAK,CACxC,IAAMC,EAAkBJ,EAAiBG,CAAC,EACpCE,EAAUR,EAASM,CAAC,EAE1B,GAAI,CAACC,GAAmB,CAACC,EACvB,MAGF,GAAID,EAAgB,WAAW,GAAG,GAAKA,EAAgB,SAAS,GAAG,EAAG,CACpE,IAAME,EAAWF,EAAgB,MAAM,EAAG,EAAE,EAE5C,GAAI,CAACE,EACH,M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,EAAE,KAAK,IAAM,CAAC,CAAC,EAE/D,KAAK,SAAW,IAAI,eAAe,CACjC,MAAQC,GAAe,CACrB,KAAKP,GAA4BO,EACjCL,EAAiB,CACnB,CACF,CAAC,EAED,KAAK,SAAW,IAAI,eAAe,CACjC,MAAQK,GAAe,CACrB,KAAKN,GAA6BM,EAClCJ,EAAkB,CACpB,EACA,MAAQK,GAAY,CAClB,KAAK,YAAYA,CAAO,CAC1B,CACF,CAAC,CACH,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,KACb,CAEA,MAAM,KAAKA,EAAyB,CAClC,GAAI,CAAC,KAAKR,GACR,MAAM,IAAI,MAAM,iCAAiC,EAEnD,KAAKA,GAA0B,QAAQQ,CAAO,CAChD,CAEA,MAAM,OAAQ,CACZ,KAAKR,IAA2B,MAAM,IAAI,MAAM,mBAAmB,CAAC,EACpE,KAAKC,IAA4B,MAAM,IAAI,MAAM,mBAAmB,CAAC,EACrE,KAAK,UAAU,CACjB,CACF","names":["Server","CallToolRequestSchema","ListResourcesRequestSchema","ListResourceTemplatesRequestSchema","ListToolsRequestSchema","ReadResourceRequestSchema","zodToJsonSchema","assertValidUri","uri","compareUris","uriA","uriB","urlA","urlB","matchUriTemplate","uriTemplates","segments","resourceUri","resourceUrl","resourceSegments","params","isMatch","i","resourceSegment","segment","paramKey","resource","uri","resourceTemplate","uriTemplate","jsonResource","jsonResourceTemplate","resources","scheme","url","jsonResourceResponse","response","tool","createMcpServer","options","capabilities","server","Server","getResources","getTools","clientInfo","clientCapabilities","initData","ListResourcesRequestSchema","name","description","mimeType","ListResourceTemplatesRequestSchema","ReadResourceRequestSchema","request","allResources","compareUris","result","resourceTemplates","resourceTemplateUris","assertValidUri","templateMatch","matchUriTemplate","r","error","enumerateError","ListToolsRequestSchema","tools","parameters","zodToJsonSchema","CallToolRequestSchema","toolName","args","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.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "MCP utilities",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
"scripts": {
|
|
11
11
|
"build": "tsup --clean",
|
|
12
12
|
"test": "vitest",
|
|
13
|
+
"test:coverage": "vitest --coverage",
|
|
13
14
|
"prepublishOnly": "npm run build"
|
|
14
15
|
},
|
|
15
16
|
"files": [
|
|
@@ -23,7 +24,7 @@
|
|
|
23
24
|
}
|
|
24
25
|
},
|
|
25
26
|
"dependencies": {
|
|
26
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
27
|
+
"@modelcontextprotocol/sdk": "^1.11.0",
|
|
27
28
|
"zod": "^3.24.1",
|
|
28
29
|
"zod-to-json-schema": "^3.24.1"
|
|
29
30
|
},
|