@supabase/mcp-utils 0.1.0 → 0.1.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 CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 o=class{#e;#r;constructor(){let r,t,s=new Promise(e=>{r=e}),a=new Promise(e=>{t=e});this.ready=Promise.all([s,a]).then(()=>{}),this.readable=new ReadableStream({start:e=>{this.#e=e,r()}}),this.writable=new WritableStream({start:e=>{this.#r=e,t()},write:e=>{_optionalChain([this, 'access', _ => _.onmessage, 'optionalCall', _2 => _2(e)])}})}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', _3 => _3.#e, 'optionalAccess', _4 => _4.error, 'call', _5 => _5(new Error("connection closed"))]),_optionalChain([this, 'access', _6 => _6.#r, 'optionalAccess', _7 => _7.error, 'call', _8 => _8(new Error("connection closed"))]),_optionalChain([this, 'access', _9 => _9.onclose, 'optionalCall', _10 => _10()])}};exports.StreamTransport = o;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 d(e){try{return new URL(e),e}catch (e2){throw new Error(`invalid uri: ${e}`)}}function y(e,t){let s=new URL(e),r=new URL(t);return s.href===r.href}function g(e,t){let r=new URL(e).pathname.split("/").slice(1);for(let i of t){let n=new URL(i),l=decodeURIComponent(n.pathname).split("/").slice(1);if(r.length!==l.length)continue;let m={},p=!0;for(let a=0;a<r.length;a++){let o=l[a],c=r[a];if(!o||!c)break;if(o.startsWith("{")&&o.endsWith("}")){let u=o.slice(1,-1);if(!u)break;m[u]=c}else if(r[a]!==l[a]){p=!1;break}}if(p)return{uri:i,params:m}}}function O(e,t){return{uri:e,...t}}function k(e,t){return{uriTemplate:e,...t}}function q(e,t){return{uri:e,mimeType:"application/json",...t}}function z(e,t){return{uriTemplate:e,mimeType:"application/json",...t}}function j(e,t){return t.map(s=>{if("uri"in s){let n=new URL(s.uri,`${e}://`),l=decodeURI(n.href);return{...s,uri:l}}let r=new URL(s.uriTemplate,`${e}://`),i=decodeURI(r.href);return{...s,uriTemplate:i}})}function M(e,t){return{uri:e,mimeType:"application/json",text:JSON.stringify(t)}}function J(e){return e}function I(e){let t={};e.resources&&(t.resources={}),e.tools&&(t.tools={});let s=new (0, _indexjs.Server)({name:e.name,version:e.version},{capabilities:t});if(s.oninitialized=()=>{let r=s.getClientVersion(),i=s.getClientCapabilities();if(!r)throw new Error("client info not available after initialization");if(!i)throw new Error("client capabilities not available after initialization");_optionalChain([e, 'access', _ => _.onInitialize, 'optionalCall', _2 => _2(r,i)])},e.resources){let r=e.resources,i=r.filter(o=>"uri"in o),n=r.filter(o=>"uriTemplate"in o),l=i.map(({uri:o,name:c,description:u,mimeType:R})=>({uri:o,name:c,description:u,mimeType:R})),m=n.map(({uriTemplate:o,name:c,description:u,mimeType:R})=>({uriTemplate:o,name:c,description:u,mimeType:R})),p=m.map(({uriTemplate:o})=>d(o));async function a(o){let c=i.find(f=>y(f.uri,o));if(c)return await c.read(o);let u=g(o,p);if(!u)throw new Error("resource not found");let R=n.find(f=>f.uriTemplate===u.uri);if(!R)throw new Error("resource not found");return await R.read(o,u.params)}s.setRequestHandler(_typesjs.ListResourcesRequestSchema,()=>({resources:l})),s.setRequestHandler(_typesjs.ListResourceTemplatesRequestSchema,()=>({resourceTemplates:m})),s.setRequestHandler(_typesjs.ReadResourceRequestSchema,async o=>{let c=await a(o.params.uri);return{contents:Array.isArray(c)?c:[c]}})}if(e.tools){let r=e.tools,i=Object.entries(r).map(([n,{description:l,parameters:m}])=>({name:n,description:l,inputSchema:_zodtojsonschema2.default.call(void 0, m)}));s.setRequestHandler(_typesjs.ListToolsRequestSchema,async()=>({tools:i})),s.setRequestHandler(_typesjs.CallToolRequestSchema,async n=>{let l=n.params.name;if(!(l in r))throw new Error("tool not found");let m=r[l];if(!m)throw new Error("tool not found");let p=n.params.arguments;if(!p)throw new Error("missing arguments");try{let a=await m.execute(p);return{content:a?[{type:"text",text:JSON.stringify(a)}]:[]}}catch(a){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:E(a)})}]}}})}return s}function E(e){if(!e||typeof e!="object")return e;let t={},s=["name","message"];for(let r of s)r in e&&(t[r]=e[r]);return t}var T=class{#e;#t;constructor(){let t,s,r=new Promise(n=>{t=n}),i=new Promise(n=>{s=n});this.ready=Promise.all([r,i]).then(()=>{}),this.readable=new ReadableStream({start:n=>{this.#e=n,t()}}),this.writable=new WritableStream({start:n=>{this.#t=n,s()},write:n=>{_optionalChain([this, 'access', _3 => _3.onmessage, 'optionalCall', _4 => _4(n)])}})}async start(){await this.ready}async send(t){if(!this.#e)throw new Error("readable stream not initialized");this.#e.enqueue(t)}async close(){_optionalChain([this, 'access', _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 = T; exports.createMcpServer = I; exports.jsonResource = q; exports.jsonResourceResponse = M; exports.jsonResourceTemplate = z; exports.resource = O; exports.resourceTemplate = k; exports.resources = j; exports.tool = J;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stream-transport.ts"],"names":["StreamTransport","#readableStreamController","#writeableStreamController","resolveReadReady","resolveWriteReady","readReady","resolve","writeReady","controller","message"],"mappings":"AAUO,ilBAAMA,CAAAA,CAAN,KAEP,CACEC,CAAAA,CAAAA,CACAC,CAAAA,CAAAA,CAEA,WASA,CAAA,CAAc,CACZ,IAAIC,CAAAA,CACAC,CAAAA,CAEEC,CAAAA,CAAY,IAAI,OAAA,CAAeC,CAAAA,EAAY,CAC/CH,CAAAA,CAAmBG,CACrB,CAAC,CAAA,CAEKC,CAAAA,CAAa,IAAI,OAAA,CAAeD,CAAAA,EAAY,CAChDF,CAAAA,CAAoBE,CACtB,CAAC,CAAA,CAED,IAAA,CAAK,KAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,CAACD,CAAAA,CAAWE,CAAU,CAAC,CAAA,CAAE,IAAA,CAAK,CAAA,CAAA,EAAM,CAAC,CAAC,CAAA,CAE/D,IAAA,CAAK,QAAA,CAAW,IAAI,cAAA,CAAe,CACjC,KAAA,CAAQC,CAAAA,EAAe,CACrB,IAAA,CAAKP,CAAAA,CAAAA,CAA4BO,CAAAA,CACjCL,CAAAA,CAAiB,CACnB,CACF,CAAC,CAAA,CAED,IAAA,CAAK,QAAA,CAAW,IAAI,cAAA,CAAe,CACjC,KAAA,CAAQK,CAAAA,EAAe,CACrB,IAAA,CAAKN,CAAAA,CAAAA,CAA6BM,CAAAA,CAClCJ,CAAAA,CAAkB,CACpB,CAAA,CACA,KAAA,CAAQK,CAAAA,EAAY,iBAClB,IAAA,mBAAK,SAAA,0BAAA,CAAYA,CAAO,GAC1B,CACF,CAAC,CACH,CAEA,MAAM,KAAA,CAAA,CAAQ,CACZ,MAAM,IAAA,CAAK,KACb,CAEA,MAAM,IAAA,CAAKA,CAAAA,CAAyB,CAClC,EAAA,CAAI,CAAC,IAAA,CAAKR,CAAAA,CAAAA,CACR,MAAM,IAAI,KAAA,CAAM,iCAAiC,CAAA,CAEnD,IAAA,CAAKA,CAAAA,CAAAA,CAA0B,OAAA,CAAQQ,CAAO,CAChD,CAEA,MAAM,KAAA,CAAA,CAAQ,iBACZ,IAAA,qBAAKR,CAAAA,CAAAA,6BAA2B,KAAA,mBAAM,IAAI,KAAA,CAAM,mBAAmB,CAAC,GAAA,iBACpE,IAAA,qBAAKC,CAAAA,CAAAA,6BAA4B,KAAA,mBAAM,IAAI,KAAA,CAAM,mBAAmB,CAAC,GAAA,iBACrE,IAAA,qBAAK,OAAA,4BAAA,CAAU,GACjB,CACF,CAAA,CAAA,4BAAA","file":"/Users/grichardson/Documents/dev/supabase/mcp-server-supabase/packages/mcp-utils/dist/index.cjs","sourcesContent":["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"]}
1
+ {"version":3,"sources":["../src/server.ts","../src/util.ts"],"names":["assertValidUri","uri"],"mappings":"AAAA,ivBAAuB,6DAYhB,uHAEqB,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 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.ZodTypeAny = z.ZodTypeAny,\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.ZodTypeAny, Result>(\n tool: Tool<Params, Result>\n) {\n return tool;\n}\n\nexport type McpServerOptions = {\n name: string;\n version: string;\n resources?: (Resource<string, unknown> | ResourceTemplate<string, unknown>)[];\n tools?: Record<string, Tool>;\n onInitialize?: (\n clientInfo: Implementation,\n clientCapabilities: ClientCapabilities\n ) => void;\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 server.oninitialized = () => {\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 options.onInitialize?.(clientInfo, clientCapabilities);\n };\n\n if (options.resources) {\n const allResources = options.resources;\n const resources = allResources.filter((resource) => 'uri' in resource);\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceList = resources.map(\n ({ uri, name, description, mimeType }) => {\n return {\n uri,\n name,\n description,\n mimeType,\n };\n }\n );\n const resourceTemplateList = resourceTemplates.map(\n ({ uriTemplate, name, description, mimeType }) => {\n return {\n uriTemplate,\n name,\n description,\n mimeType,\n };\n }\n );\n\n const resourceTemplateUris = resourceTemplateList.map(({ uriTemplate }) =>\n assertValidUri(uriTemplate)\n );\n\n async function readResource(uri: string) {\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 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 return await resourceTemplate.read(\n uri as `${string}://${string}`,\n templateMatch.params\n );\n }\n\n server.setRequestHandler(\n ListResourcesRequestSchema,\n (): ListResourcesResult => {\n return {\n resources: resourceList,\n };\n }\n );\n\n server.setRequestHandler(\n ListResourceTemplatesRequestSchema,\n (): ListResourceTemplatesResult => {\n return {\n resourceTemplates: resourceTemplateList,\n };\n }\n );\n\n server.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const result = await readResource(request.params.uri);\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n });\n }\n\n if (options.tools) {\n const tools = options.tools;\n const toolList = Object.entries(tools).map(\n ([name, { description, parameters }]) => {\n return {\n name,\n description,\n inputSchema: zodToJsonSchema(parameters),\n };\n }\n );\n\n type Tools = typeof tools;\n type ToolName = keyof Tools;\n type Tool = Tools[ToolName];\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: toolList,\n };\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const toolName = request.params.name as ToolName;\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 = request.params.arguments as z.infer<Tool['parameters']>;\n\n if (!args) {\n throw new Error('missing arguments');\n }\n\n try {\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
@@ -1,10 +1,134 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { Implementation, ClientCapabilities, JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
3
+ import { z } from 'zod';
1
4
  import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
2
- import { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
3
5
 
6
+ /**
7
+ * A web stream that can be both read from and written to.
8
+ */
4
9
  interface DuplexStream<T> {
5
10
  readable: ReadableStream<T>;
6
11
  writable: WritableStream<T>;
7
12
  }
13
+ /**
14
+ * Expands a type into its properties recursively.
15
+ *
16
+ * Useful for providing better intellisense in IDEs.
17
+ */
18
+ type ExpandRecursively<T> = T extends (...args: infer A) => infer R ? (...args: ExpandRecursively<A>) => ExpandRecursively<R> : T extends object ? T extends infer O ? {
19
+ [K in keyof O]: ExpandRecursively<O[K]>;
20
+ } : never : T;
21
+ /**
22
+ * Extracts parameter names from a string path.
23
+ *
24
+ * @example
25
+ * type Path = '/schemas/{schema}/tables/{table}';
26
+ * type Params = ExtractParams<Path>; // 'schema' | 'table'
27
+ */
28
+ type ExtractParams<Path extends string> = Path extends `${string}{${infer P}}${infer Rest}` ? P | ExtractParams<Rest> : never;
29
+ /**
30
+ * Extracts the request type from an MCP server.
31
+ */
32
+ type ExtractRequest<S> = S extends Server<infer R, any, any> ? R : never;
33
+ /**
34
+ * Extracts the notification type from an MCP server.
35
+ */
36
+ type ExtractNotification<S> = S extends Server<any, infer N, any> ? N : never;
37
+ /**
38
+ * Extracts the result type from an MCP server.
39
+ */
40
+ type ExtractResult<S> = S extends Server<any, any, infer R> ? R : never;
41
+
42
+ type Scheme = string;
43
+ type Resource<Uri extends string = string, Result = unknown> = {
44
+ uri: Uri;
45
+ name: string;
46
+ description?: string;
47
+ mimeType?: string;
48
+ read(uri: `${Scheme}://${Uri}`): Promise<Result>;
49
+ };
50
+ type ResourceTemplate<Uri extends string = string, Result = unknown> = {
51
+ uriTemplate: Uri;
52
+ name: string;
53
+ description?: string;
54
+ mimeType?: string;
55
+ read(uri: `${Scheme}://${Uri}`, params: {
56
+ [Param in ExtractParams<Uri>]: string;
57
+ }): Promise<Result>;
58
+ };
59
+ type Tool<Params extends z.ZodTypeAny = z.ZodTypeAny, Result = unknown> = {
60
+ description: string;
61
+ parameters: Params;
62
+ execute(params: z.infer<Params>): Promise<Result>;
63
+ };
64
+ /**
65
+ * Helper function to define an MCP resource while preserving type information.
66
+ */
67
+ declare function resource<Uri extends string, Result>(uri: Uri, resource: Omit<Resource<Uri, Result>, 'uri'>): Resource<Uri, Result>;
68
+ /**
69
+ * Helper function to define an MCP resource with a URI template while preserving type information.
70
+ */
71
+ declare function resourceTemplate<Uri extends string, Result>(uriTemplate: Uri, resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>): ResourceTemplate<Uri, Result>;
72
+ /**
73
+ * Helper function to define a JSON resource while preserving type information.
74
+ */
75
+ declare function jsonResource<Uri extends string, Result>(uri: Uri, resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>): Resource<Uri, Result>;
76
+ /**
77
+ * Helper function to define a JSON resource with a URI template while preserving type information.
78
+ */
79
+ declare function jsonResourceTemplate<Uri extends string, Result>(uriTemplate: Uri, resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>): ResourceTemplate<Uri, Result>;
80
+ /**
81
+ * Helper function to define a list of resources that share a common URI scheme.
82
+ */
83
+ declare function resources<Scheme extends string>(scheme: Scheme, resources: (Resource | ResourceTemplate)[]): (Resource<`${Scheme}://${string}`> | ResourceTemplate<`${Scheme}://${string}`>)[];
84
+ /**
85
+ * Helper function to create a JSON resource response.
86
+ */
87
+ declare function jsonResourceResponse<Uri extends string, Response>(uri: Uri, response: Response): {
88
+ uri: Uri;
89
+ mimeType: string;
90
+ text: string;
91
+ };
92
+ /**
93
+ * Helper function to define an MCP tool while preserving type information.
94
+ */
95
+ declare function tool<Params extends z.ZodTypeAny, Result>(tool: Tool<Params, Result>): Tool<Params, Result>;
96
+ type McpServerOptions = {
97
+ name: string;
98
+ version: string;
99
+ resources?: (Resource<string, unknown> | ResourceTemplate<string, unknown>)[];
100
+ tools?: Record<string, Tool>;
101
+ onInitialize?: (clientInfo: Implementation, clientCapabilities: ClientCapabilities) => void;
102
+ };
103
+ /**
104
+ * Creates an MCP server with the given options.
105
+ *
106
+ * Simplifies the process of creating an MCP server by providing a high-level
107
+ * API for defining resources and tools.
108
+ */
109
+ declare function createMcpServer(options: McpServerOptions): Server<{
110
+ method: string;
111
+ params?: {
112
+ [x: string]: unknown;
113
+ _meta?: {
114
+ [x: string]: unknown;
115
+ progressToken?: string | number | undefined;
116
+ } | undefined;
117
+ } | undefined;
118
+ }, {
119
+ method: string;
120
+ params?: {
121
+ [x: string]: unknown;
122
+ _meta?: {
123
+ [x: string]: unknown;
124
+ } | undefined;
125
+ } | undefined;
126
+ }, {
127
+ [x: string]: unknown;
128
+ _meta?: {
129
+ [x: string]: unknown;
130
+ } | undefined;
131
+ }>;
8
132
 
9
133
  /**
10
134
  * An MCP transport built on top of a duplex stream.
@@ -26,4 +150,4 @@ declare class StreamTransport implements Transport, DuplexStream<JSONRPCMessage>
26
150
  close(): Promise<void>;
27
151
  }
28
152
 
29
- export { type DuplexStream, StreamTransport };
153
+ export { type DuplexStream, type ExpandRecursively, type ExtractNotification, type ExtractParams, type ExtractRequest, type ExtractResult, type McpServerOptions, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, createMcpServer, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,134 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { Implementation, ClientCapabilities, JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
3
+ import { z } from 'zod';
1
4
  import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
2
- import { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
3
5
 
6
+ /**
7
+ * A web stream that can be both read from and written to.
8
+ */
4
9
  interface DuplexStream<T> {
5
10
  readable: ReadableStream<T>;
6
11
  writable: WritableStream<T>;
7
12
  }
13
+ /**
14
+ * Expands a type into its properties recursively.
15
+ *
16
+ * Useful for providing better intellisense in IDEs.
17
+ */
18
+ type ExpandRecursively<T> = T extends (...args: infer A) => infer R ? (...args: ExpandRecursively<A>) => ExpandRecursively<R> : T extends object ? T extends infer O ? {
19
+ [K in keyof O]: ExpandRecursively<O[K]>;
20
+ } : never : T;
21
+ /**
22
+ * Extracts parameter names from a string path.
23
+ *
24
+ * @example
25
+ * type Path = '/schemas/{schema}/tables/{table}';
26
+ * type Params = ExtractParams<Path>; // 'schema' | 'table'
27
+ */
28
+ type ExtractParams<Path extends string> = Path extends `${string}{${infer P}}${infer Rest}` ? P | ExtractParams<Rest> : never;
29
+ /**
30
+ * Extracts the request type from an MCP server.
31
+ */
32
+ type ExtractRequest<S> = S extends Server<infer R, any, any> ? R : never;
33
+ /**
34
+ * Extracts the notification type from an MCP server.
35
+ */
36
+ type ExtractNotification<S> = S extends Server<any, infer N, any> ? N : never;
37
+ /**
38
+ * Extracts the result type from an MCP server.
39
+ */
40
+ type ExtractResult<S> = S extends Server<any, any, infer R> ? R : never;
41
+
42
+ type Scheme = string;
43
+ type Resource<Uri extends string = string, Result = unknown> = {
44
+ uri: Uri;
45
+ name: string;
46
+ description?: string;
47
+ mimeType?: string;
48
+ read(uri: `${Scheme}://${Uri}`): Promise<Result>;
49
+ };
50
+ type ResourceTemplate<Uri extends string = string, Result = unknown> = {
51
+ uriTemplate: Uri;
52
+ name: string;
53
+ description?: string;
54
+ mimeType?: string;
55
+ read(uri: `${Scheme}://${Uri}`, params: {
56
+ [Param in ExtractParams<Uri>]: string;
57
+ }): Promise<Result>;
58
+ };
59
+ type Tool<Params extends z.ZodTypeAny = z.ZodTypeAny, Result = unknown> = {
60
+ description: string;
61
+ parameters: Params;
62
+ execute(params: z.infer<Params>): Promise<Result>;
63
+ };
64
+ /**
65
+ * Helper function to define an MCP resource while preserving type information.
66
+ */
67
+ declare function resource<Uri extends string, Result>(uri: Uri, resource: Omit<Resource<Uri, Result>, 'uri'>): Resource<Uri, Result>;
68
+ /**
69
+ * Helper function to define an MCP resource with a URI template while preserving type information.
70
+ */
71
+ declare function resourceTemplate<Uri extends string, Result>(uriTemplate: Uri, resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>): ResourceTemplate<Uri, Result>;
72
+ /**
73
+ * Helper function to define a JSON resource while preserving type information.
74
+ */
75
+ declare function jsonResource<Uri extends string, Result>(uri: Uri, resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>): Resource<Uri, Result>;
76
+ /**
77
+ * Helper function to define a JSON resource with a URI template while preserving type information.
78
+ */
79
+ declare function jsonResourceTemplate<Uri extends string, Result>(uriTemplate: Uri, resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>): ResourceTemplate<Uri, Result>;
80
+ /**
81
+ * Helper function to define a list of resources that share a common URI scheme.
82
+ */
83
+ declare function resources<Scheme extends string>(scheme: Scheme, resources: (Resource | ResourceTemplate)[]): (Resource<`${Scheme}://${string}`> | ResourceTemplate<`${Scheme}://${string}`>)[];
84
+ /**
85
+ * Helper function to create a JSON resource response.
86
+ */
87
+ declare function jsonResourceResponse<Uri extends string, Response>(uri: Uri, response: Response): {
88
+ uri: Uri;
89
+ mimeType: string;
90
+ text: string;
91
+ };
92
+ /**
93
+ * Helper function to define an MCP tool while preserving type information.
94
+ */
95
+ declare function tool<Params extends z.ZodTypeAny, Result>(tool: Tool<Params, Result>): Tool<Params, Result>;
96
+ type McpServerOptions = {
97
+ name: string;
98
+ version: string;
99
+ resources?: (Resource<string, unknown> | ResourceTemplate<string, unknown>)[];
100
+ tools?: Record<string, Tool>;
101
+ onInitialize?: (clientInfo: Implementation, clientCapabilities: ClientCapabilities) => void;
102
+ };
103
+ /**
104
+ * Creates an MCP server with the given options.
105
+ *
106
+ * Simplifies the process of creating an MCP server by providing a high-level
107
+ * API for defining resources and tools.
108
+ */
109
+ declare function createMcpServer(options: McpServerOptions): Server<{
110
+ method: string;
111
+ params?: {
112
+ [x: string]: unknown;
113
+ _meta?: {
114
+ [x: string]: unknown;
115
+ progressToken?: string | number | undefined;
116
+ } | undefined;
117
+ } | undefined;
118
+ }, {
119
+ method: string;
120
+ params?: {
121
+ [x: string]: unknown;
122
+ _meta?: {
123
+ [x: string]: unknown;
124
+ } | undefined;
125
+ } | undefined;
126
+ }, {
127
+ [x: string]: unknown;
128
+ _meta?: {
129
+ [x: string]: unknown;
130
+ } | undefined;
131
+ }>;
8
132
 
9
133
  /**
10
134
  * An MCP transport built on top of a duplex stream.
@@ -26,4 +150,4 @@ declare class StreamTransport implements Transport, DuplexStream<JSONRPCMessage>
26
150
  close(): Promise<void>;
27
151
  }
28
152
 
29
- export { type DuplexStream, StreamTransport };
153
+ export { type DuplexStream, type ExpandRecursively, type ExtractNotification, type ExtractParams, type ExtractRequest, type ExtractResult, type McpServerOptions, 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
- var o=class{#e;#r;ready;readable;writable;onclose;onerror;onmessage;constructor(){let r,t,s=new Promise(e=>{r=e}),a=new Promise(e=>{t=e});this.ready=Promise.all([s,a]).then(()=>{}),this.readable=new ReadableStream({start:e=>{this.#e=e,r()}}),this.writable=new WritableStream({start:e=>{this.#r=e,t()},write:e=>{this.onmessage?.(e)}})}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.#r?.error(new Error("connection closed")),this.onclose?.()}};export{o as StreamTransport};
1
+ import{Server as x}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as h,ListResourcesRequestSchema as w,ListResourceTemplatesRequestSchema as S,ListToolsRequestSchema as U,ReadResourceRequestSchema as b}from"@modelcontextprotocol/sdk/types.js";import v from"zod-to-json-schema";function d(e){try{return new URL(e),e}catch{throw new Error(`invalid uri: ${e}`)}}function y(e,t){let s=new URL(e),r=new URL(t);return s.href===r.href}function g(e,t){let r=new URL(e).pathname.split("/").slice(1);for(let i of t){let n=new URL(i),l=decodeURIComponent(n.pathname).split("/").slice(1);if(r.length!==l.length)continue;let m={},p=!0;for(let a=0;a<r.length;a++){let o=l[a],c=r[a];if(!o||!c)break;if(o.startsWith("{")&&o.endsWith("}")){let u=o.slice(1,-1);if(!u)break;m[u]=c}else if(r[a]!==l[a]){p=!1;break}}if(p)return{uri:i,params:m}}}function O(e,t){return{uri:e,...t}}function k(e,t){return{uriTemplate:e,...t}}function q(e,t){return{uri:e,mimeType:"application/json",...t}}function z(e,t){return{uriTemplate:e,mimeType:"application/json",...t}}function j(e,t){return t.map(s=>{if("uri"in s){let n=new URL(s.uri,`${e}://`),l=decodeURI(n.href);return{...s,uri:l}}let r=new URL(s.uriTemplate,`${e}://`),i=decodeURI(r.href);return{...s,uriTemplate:i}})}function M(e,t){return{uri:e,mimeType:"application/json",text:JSON.stringify(t)}}function J(e){return e}function I(e){let t={};e.resources&&(t.resources={}),e.tools&&(t.tools={});let s=new x({name:e.name,version:e.version},{capabilities:t});if(s.oninitialized=()=>{let r=s.getClientVersion(),i=s.getClientCapabilities();if(!r)throw new Error("client info not available after initialization");if(!i)throw new Error("client capabilities not available after initialization");e.onInitialize?.(r,i)},e.resources){let r=e.resources,i=r.filter(o=>"uri"in o),n=r.filter(o=>"uriTemplate"in o),l=i.map(({uri:o,name:c,description:u,mimeType:R})=>({uri:o,name:c,description:u,mimeType:R})),m=n.map(({uriTemplate:o,name:c,description:u,mimeType:R})=>({uriTemplate:o,name:c,description:u,mimeType:R})),p=m.map(({uriTemplate:o})=>d(o));async function a(o){let c=i.find(f=>y(f.uri,o));if(c)return await c.read(o);let u=g(o,p);if(!u)throw new Error("resource not found");let R=n.find(f=>f.uriTemplate===u.uri);if(!R)throw new Error("resource not found");return await R.read(o,u.params)}s.setRequestHandler(w,()=>({resources:l})),s.setRequestHandler(S,()=>({resourceTemplates:m})),s.setRequestHandler(b,async o=>{let c=await a(o.params.uri);return{contents:Array.isArray(c)?c:[c]}})}if(e.tools){let r=e.tools,i=Object.entries(r).map(([n,{description:l,parameters:m}])=>({name:n,description:l,inputSchema:v(m)}));s.setRequestHandler(U,async()=>({tools:i})),s.setRequestHandler(h,async n=>{let l=n.params.name;if(!(l in r))throw new Error("tool not found");let m=r[l];if(!m)throw new Error("tool not found");let p=n.params.arguments;if(!p)throw new Error("missing arguments");try{let a=await m.execute(p);return{content:a?[{type:"text",text:JSON.stringify(a)}]:[]}}catch(a){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:E(a)})}]}}})}return s}function E(e){if(!e||typeof e!="object")return e;let t={},s=["name","message"];for(let r of s)r in e&&(t[r]=e[r]);return t}var T=class{#e;#t;ready;readable;writable;onclose;onerror;onmessage;constructor(){let t,s,r=new Promise(n=>{t=n}),i=new Promise(n=>{s=n});this.ready=Promise.all([r,i]).then(()=>{}),this.readable=new ReadableStream({start:n=>{this.#e=n,t()}}),this.writable=new WritableStream({start:n=>{this.#t=n,s()},write:n=>{this.onmessage?.(n)}})}async start(){await this.ready}async send(t){if(!this.#e)throw new Error("readable stream not initialized");this.#e.enqueue(t)}async close(){this.#e?.error(new Error("connection closed")),this.#t?.error(new Error("connection closed")),this.onclose?.()}};export{T as StreamTransport,I as createMcpServer,q as jsonResource,M as jsonResourceResponse,z as jsonResourceTemplate,O as resource,k as resourceTemplate,j as resources,J as tool};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/stream-transport.ts"],"sourcesContent":["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":"AAUO,IAAMA,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":["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 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.ZodTypeAny = z.ZodTypeAny,\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.ZodTypeAny, Result>(\n tool: Tool<Params, Result>\n) {\n return tool;\n}\n\nexport type McpServerOptions = {\n name: string;\n version: string;\n resources?: (Resource<string, unknown> | ResourceTemplate<string, unknown>)[];\n tools?: Record<string, Tool>;\n onInitialize?: (\n clientInfo: Implementation,\n clientCapabilities: ClientCapabilities\n ) => void;\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 server.oninitialized = () => {\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 options.onInitialize?.(clientInfo, clientCapabilities);\n };\n\n if (options.resources) {\n const allResources = options.resources;\n const resources = allResources.filter((resource) => 'uri' in resource);\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceList = resources.map(\n ({ uri, name, description, mimeType }) => {\n return {\n uri,\n name,\n description,\n mimeType,\n };\n }\n );\n const resourceTemplateList = resourceTemplates.map(\n ({ uriTemplate, name, description, mimeType }) => {\n return {\n uriTemplate,\n name,\n description,\n mimeType,\n };\n }\n );\n\n const resourceTemplateUris = resourceTemplateList.map(({ uriTemplate }) =>\n assertValidUri(uriTemplate)\n );\n\n async function readResource(uri: string) {\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 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 return await resourceTemplate.read(\n uri as `${string}://${string}`,\n templateMatch.params\n );\n }\n\n server.setRequestHandler(\n ListResourcesRequestSchema,\n (): ListResourcesResult => {\n return {\n resources: resourceList,\n };\n }\n );\n\n server.setRequestHandler(\n ListResourceTemplatesRequestSchema,\n (): ListResourceTemplatesResult => {\n return {\n resourceTemplates: resourceTemplateList,\n };\n }\n );\n\n server.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const result = await readResource(request.params.uri);\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n });\n }\n\n if (options.tools) {\n const tools = options.tools;\n const toolList = Object.entries(tools).map(\n ([name, { description, parameters }]) => {\n return {\n name,\n description,\n inputSchema: zodToJsonSchema(parameters),\n };\n }\n );\n\n type Tools = typeof tools;\n type ToolName = keyof Tools;\n type Tool = Tools[ToolName];\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: toolList,\n };\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const toolName = request.params.name as ToolName;\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 = request.params.arguments as z.infer<Tool['parameters']>;\n\n if (!args) {\n throw new Error('missing arguments');\n }\n\n try {\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,qCAEP,OAAOC,MAAqB,qBCTrB,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,CA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AQ,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","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","clientInfo","clientCapabilities","allResources","resourceTemplates","resourceList","name","description","mimeType","resourceTemplateList","resourceTemplateUris","assertValidUri","readResource","compareUris","templateMatch","matchUriTemplate","r","ListResourcesRequestSchema","ListResourceTemplatesRequestSchema","ReadResourceRequestSchema","request","result","tools","toolList","parameters","zodToJsonSchema","ListToolsRequestSchema","CallToolRequestSchema","toolName","args","error","enumerateError","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.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "MCP utilities",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -9,6 +9,7 @@
9
9
  "sideEffects": false,
10
10
  "scripts": {
11
11
  "build": "tsup --clean",
12
+ "test": "vitest",
12
13
  "prepublishOnly": "npm run build"
13
14
  },
14
15
  "files": [
@@ -21,13 +22,17 @@
21
22
  "default": "./dist/index.cjs"
22
23
  }
23
24
  },
24
- "dependencies": {},
25
+ "dependencies": {
26
+ "@modelcontextprotocol/sdk": "^1.4.1",
27
+ "zod": "^3.24.1",
28
+ "zod-to-json-schema": "^3.24.1"
29
+ },
25
30
  "devDependencies": {
26
- "@modelcontextprotocol/sdk": "^1.0.4",
27
31
  "@total-typescript/tsconfig": "^1.0.4",
28
32
  "@types/node": "^22.8.6",
29
33
  "prettier": "^3.3.3",
30
34
  "tsup": "^8.3.5",
31
- "typescript": "^5.6.3"
35
+ "typescript": "^5.6.3",
36
+ "vitest": "^2.1.8"
32
37
  }
33
38
  }