@supabase/mcp-utils 0.2.0 → 0.2.2
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/LICENSE +201 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -14
- package/dist/index.d.ts +16 -14
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +11 -8
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Supabase
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
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 l=t[a],R=n[a];if(!l||!R)break;if(l.startsWith("{")&&l.endsWith("}")){let p=l.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 q(e,r){return{uri:e,...r}}function I(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 A(e){return e}function W(e){let r={};e.resources&&(r.resources={}),e.tools&&(r.tools={});let o=new (0, _indexjs.Server)({name:e.name,title:e.title,version:e.version},{capabilities:r});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(u=>"uri"in u).find(u=>g(u.uri,i));if(a){let u=await a.read(i);return{contents:Array.isArray(u)?u:[u]}}let l=t.filter(u=>"uriTemplate"in u),R=l.map(({uriTemplate:u})=>y(u)),p=x(i,R);if(!p)throw new Error("resource not found");let d=l.find(u=>u.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,annotations:c,parameters:a}])=>{let l=_zodtojsonschema2.default.call(void 0, a);if(!("properties"in l))throw new Error("tool parameters must be a ZodObject");return{name:t,description:i,annotations:c,inputSchema:l}})}}),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, () => ({}))),l=await c.execute(a);return{content:l?[{type:"text",text:JSON.stringify(l)}]:[]}}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 = W; exports.jsonResource = z; exports.jsonResourceResponse = D; exports.jsonResourceTemplate = J; exports.resource = q; exports.resourceTemplate = I; exports.resources = M; exports.tool = A;
|
|
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,6DAchB,uHAEqB,SCXZA,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 type ListToolsResult,\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;\nexport type Annotations = NonNullable<\n ListToolsResult['tools'][number]['annotations']\n>;\n\nexport type Resource<Uri extends string = string, Result = unknown> = {\n uri: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(uri: `${Scheme}://${Uri}`): Promise<Result>;\n};\n\nexport type ResourceTemplate<Uri extends string = string, Result = unknown> = {\n uriTemplate: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(\n uri: `${Scheme}://${Uri}`,\n params: {\n [Param in ExtractParams<Uri>]: string;\n }\n ): Promise<Result>;\n};\n\nexport type Tool<\n Params extends z.ZodObject<any> = z.ZodObject<any>,\n Result = unknown,\n> = {\n description: string;\n annotations?: Annotations;\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 title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?: Prop<Record<string, Tool>>;\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer(options: McpServerOptions) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools() {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools()\n : options.tools;\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n ListResourcesRequestSchema,\n async (): Promise<ListResourcesResult> => {\n const allResources = await getResources();\n return {\n resources: allResources\n .filter((resource) => 'uri' in resource)\n .map(({ uri, name, description, mimeType }) => {\n return {\n uri,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n ListResourceTemplatesRequestSchema,\n async (): Promise<ListResourceTemplatesResult> => {\n const allResources = await getResources();\n return {\n resourceTemplates: allResources\n .filter((resource) => 'uriTemplate' in resource)\n .map(({ uriTemplate, name, description, mimeType }) => {\n return {\n uriTemplate,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request): Promise<ReadResourceResult> => {\n try {\n const allResources = await getResources();\n const { uri } = request.params;\n\n const resources = allResources.filter(\n (resource) => 'uri' in resource\n );\n const resource = resources.find((resource) =>\n compareUris(resource.uri, uri)\n );\n\n if (resource) {\n const result = await resource.read(uri as `${string}://${string}`);\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n }\n\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceTemplateUris = resourceTemplates.map(\n ({ uriTemplate }) => assertValidUri(uriTemplate)\n );\n\n const templateMatch = matchUriTemplate(uri, resourceTemplateUris);\n\n if (!templateMatch) {\n throw new Error('resource not found');\n }\n\n const resourceTemplate = resourceTemplates.find(\n (r) => r.uriTemplate === templateMatch.uri\n );\n\n if (!resourceTemplate) {\n throw new Error('resource not found');\n }\n\n const result = await resourceTemplate.read(\n uri as `${string}://${string}`,\n templateMatch.params\n );\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n } catch (error) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } as any;\n }\n }\n );\n }\n\n if (options.tools) {\n server.setRequestHandler(\n ListToolsRequestSchema,\n async (): Promise<ListToolsResult> => {\n const tools = await getTools();\n return {\n tools: Object.entries(tools).map(\n ([name, { description, annotations, parameters }]) => {\n const inputSchema = zodToJsonSchema(parameters);\n\n if (!('properties' in inputSchema)) {\n throw new Error('tool parameters must be a ZodObject');\n }\n\n return {\n name,\n description,\n annotations,\n inputSchema,\n };\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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
-
import { Implementation, ClientCapabilities, JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
|
|
2
|
+
import { ListToolsResult, Implementation, ClientCapabilities, JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
|
|
5
5
|
|
|
@@ -40,6 +40,7 @@ type ExtractNotification<S> = S extends Server<any, infer N, any> ? N : never;
|
|
|
40
40
|
type ExtractResult<S> = S extends Server<any, any, infer R> ? R : never;
|
|
41
41
|
|
|
42
42
|
type Scheme = string;
|
|
43
|
+
type Annotations = NonNullable<ListToolsResult['tools'][number]['annotations']>;
|
|
43
44
|
type Resource<Uri extends string = string, Result = unknown> = {
|
|
44
45
|
uri: Uri;
|
|
45
46
|
name: string;
|
|
@@ -58,6 +59,7 @@ type ResourceTemplate<Uri extends string = string, Result = unknown> = {
|
|
|
58
59
|
};
|
|
59
60
|
type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, Result = unknown> = {
|
|
60
61
|
description: string;
|
|
62
|
+
annotations?: Annotations;
|
|
61
63
|
parameters: Params;
|
|
62
64
|
execute(params: z.infer<Params>): Promise<Result>;
|
|
63
65
|
};
|
|
@@ -97,7 +99,8 @@ type InitData = {
|
|
|
97
99
|
clientInfo: Implementation;
|
|
98
100
|
clientCapabilities: ClientCapabilities;
|
|
99
101
|
};
|
|
100
|
-
type
|
|
102
|
+
type InitCallback = (initData: InitData) => void | Promise<void>;
|
|
103
|
+
type PropCallback<T> = () => T | Promise<T>;
|
|
101
104
|
type Prop<T> = T | PropCallback<T>;
|
|
102
105
|
type McpServerOptions = {
|
|
103
106
|
/**
|
|
@@ -105,6 +108,13 @@ type McpServerOptions = {
|
|
|
105
108
|
* the initialization process.
|
|
106
109
|
*/
|
|
107
110
|
name: string;
|
|
111
|
+
/**
|
|
112
|
+
* The title of the MCP server. This is a human-readable name that can be
|
|
113
|
+
* displayed in the client UI.
|
|
114
|
+
*
|
|
115
|
+
* If not provided, the name will be used as the title.
|
|
116
|
+
*/
|
|
117
|
+
title?: string;
|
|
108
118
|
/**
|
|
109
119
|
* The version of the MCP server. This will be sent to the client as part of
|
|
110
120
|
* the initialization process.
|
|
@@ -112,14 +122,8 @@ type McpServerOptions = {
|
|
|
112
122
|
version: string;
|
|
113
123
|
/**
|
|
114
124
|
* 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
125
|
*/
|
|
122
|
-
onInitialize?:
|
|
126
|
+
onInitialize?: InitCallback;
|
|
123
127
|
/**
|
|
124
128
|
* Resources to be served by the server. These can be defined as a static
|
|
125
129
|
* object or as a function that dynamically returns the object synchronously
|
|
@@ -127,8 +131,7 @@ type McpServerOptions = {
|
|
|
127
131
|
*
|
|
128
132
|
* If defined as a function, the function will be called whenever the client
|
|
129
133
|
* 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.
|
|
134
|
+
* resources that can change after the server has started.
|
|
132
135
|
*/
|
|
133
136
|
resources?: Prop<(Resource<string, unknown> | ResourceTemplate<string, unknown>)[]>;
|
|
134
137
|
/**
|
|
@@ -138,8 +141,7 @@ type McpServerOptions = {
|
|
|
138
141
|
*
|
|
139
142
|
* If defined as a function, the function will be called whenever the client
|
|
140
143
|
* 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.
|
|
144
|
+
* that can change after the server has started.
|
|
143
145
|
*/
|
|
144
146
|
tools?: Prop<Record<string, Tool>>;
|
|
145
147
|
};
|
|
@@ -193,4 +195,4 @@ declare class StreamTransport implements Transport, DuplexStream<JSONRPCMessage>
|
|
|
193
195
|
close(): Promise<void>;
|
|
194
196
|
}
|
|
195
197
|
|
|
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 };
|
|
198
|
+
export { type Annotations, 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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
-
import { Implementation, ClientCapabilities, JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
|
|
2
|
+
import { ListToolsResult, Implementation, ClientCapabilities, JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
|
|
5
5
|
|
|
@@ -40,6 +40,7 @@ type ExtractNotification<S> = S extends Server<any, infer N, any> ? N : never;
|
|
|
40
40
|
type ExtractResult<S> = S extends Server<any, any, infer R> ? R : never;
|
|
41
41
|
|
|
42
42
|
type Scheme = string;
|
|
43
|
+
type Annotations = NonNullable<ListToolsResult['tools'][number]['annotations']>;
|
|
43
44
|
type Resource<Uri extends string = string, Result = unknown> = {
|
|
44
45
|
uri: Uri;
|
|
45
46
|
name: string;
|
|
@@ -58,6 +59,7 @@ type ResourceTemplate<Uri extends string = string, Result = unknown> = {
|
|
|
58
59
|
};
|
|
59
60
|
type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, Result = unknown> = {
|
|
60
61
|
description: string;
|
|
62
|
+
annotations?: Annotations;
|
|
61
63
|
parameters: Params;
|
|
62
64
|
execute(params: z.infer<Params>): Promise<Result>;
|
|
63
65
|
};
|
|
@@ -97,7 +99,8 @@ type InitData = {
|
|
|
97
99
|
clientInfo: Implementation;
|
|
98
100
|
clientCapabilities: ClientCapabilities;
|
|
99
101
|
};
|
|
100
|
-
type
|
|
102
|
+
type InitCallback = (initData: InitData) => void | Promise<void>;
|
|
103
|
+
type PropCallback<T> = () => T | Promise<T>;
|
|
101
104
|
type Prop<T> = T | PropCallback<T>;
|
|
102
105
|
type McpServerOptions = {
|
|
103
106
|
/**
|
|
@@ -105,6 +108,13 @@ type McpServerOptions = {
|
|
|
105
108
|
* the initialization process.
|
|
106
109
|
*/
|
|
107
110
|
name: string;
|
|
111
|
+
/**
|
|
112
|
+
* The title of the MCP server. This is a human-readable name that can be
|
|
113
|
+
* displayed in the client UI.
|
|
114
|
+
*
|
|
115
|
+
* If not provided, the name will be used as the title.
|
|
116
|
+
*/
|
|
117
|
+
title?: string;
|
|
108
118
|
/**
|
|
109
119
|
* The version of the MCP server. This will be sent to the client as part of
|
|
110
120
|
* the initialization process.
|
|
@@ -112,14 +122,8 @@ type McpServerOptions = {
|
|
|
112
122
|
version: string;
|
|
113
123
|
/**
|
|
114
124
|
* 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
125
|
*/
|
|
122
|
-
onInitialize?:
|
|
126
|
+
onInitialize?: InitCallback;
|
|
123
127
|
/**
|
|
124
128
|
* Resources to be served by the server. These can be defined as a static
|
|
125
129
|
* object or as a function that dynamically returns the object synchronously
|
|
@@ -127,8 +131,7 @@ type McpServerOptions = {
|
|
|
127
131
|
*
|
|
128
132
|
* If defined as a function, the function will be called whenever the client
|
|
129
133
|
* 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.
|
|
134
|
+
* resources that can change after the server has started.
|
|
132
135
|
*/
|
|
133
136
|
resources?: Prop<(Resource<string, unknown> | ResourceTemplate<string, unknown>)[]>;
|
|
134
137
|
/**
|
|
@@ -138,8 +141,7 @@ type McpServerOptions = {
|
|
|
138
141
|
*
|
|
139
142
|
* If defined as a function, the function will be called whenever the client
|
|
140
143
|
* 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.
|
|
144
|
+
* that can change after the server has started.
|
|
143
145
|
*/
|
|
144
146
|
tools?: Prop<Record<string, Tool>>;
|
|
145
147
|
};
|
|
@@ -193,4 +195,4 @@ declare class StreamTransport implements Transport, DuplexStream<JSONRPCMessage>
|
|
|
193
195
|
close(): Promise<void>;
|
|
194
196
|
}
|
|
195
197
|
|
|
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 };
|
|
198
|
+
export { type Annotations, 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 b,ListResourcesRequestSchema as S,ListResourceTemplatesRequestSchema as U,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 l=t[a],R=n[a];if(!l||!R)break;if(l.startsWith("{")&&l.endsWith("}")){let p=l.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 q(e,r){return{uri:e,...r}}function I(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 A(e){return e}function W(e){let r={};e.resources&&(r.resources={}),e.tools&&(r.tools={});let o=new T({name:e.name,title:e.title,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(S,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(U,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(u=>"uri"in u).find(u=>g(u.uri,i));if(a){let u=await a.read(i);return{contents:Array.isArray(u)?u:[u]}}let l=t.filter(u=>"uriTemplate"in u),R=l.map(({uriTemplate:u})=>y(u)),p=x(i,R);if(!p)throw new Error("resource not found");let d=l.find(u=>u.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,annotations:c,parameters:a}])=>{let l=E(a);if(!("properties"in l))throw new Error("tool parameters must be a ZodObject");return{name:t,description:i,annotations:c,inputSchema:l}})}}),o.setRequestHandler(b,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??{}),l=await c.execute(a);return{content:l?[{type:"text",text:JSON.stringify(l)}]:[]}}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,W as createMcpServer,z as jsonResource,D as jsonResourceResponse,J as jsonResourceTemplate,q as resource,I as resourceTemplate,M as resources,A as tool};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/util.ts","../src/stream-transport.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport {\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n ReadResourceRequestSchema,\n type ClientCapabilities,\n type Implementation,\n type ListResourcesResult,\n type ListResourceTemplatesResult,\n type 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,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,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,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OAAQ,SAAS,EAErC,QAAWC,KAAQD,EACbC,KAAQX,IACVS,EAASE,CAAI,EAAKX,EAAkCW,CAAI,GAI5D,OAAOF,CACT,CE3dO,IAAMG,EAAN,KAEP,CACEC,GACAC,GAEA,MAEA,SACA,SAEA,QACA,QACA,UAEA,aAAc,CACZ,IAAIC,EACAC,EAEEC,EAAY,IAAI,QAAeC,GAAY,CAC/CH,EAAmBG,CACrB,CAAC,EAEKC,EAAa,IAAI,QAAeD,GAAY,CAChDF,EAAoBE,CACtB,CAAC,EAED,KAAK,MAAQ,QAAQ,IAAI,CAACD,EAAWE,CAAU,CAAC,EAAE,KAAK,IAAM,CAAC,CAAC,EAE/D,KAAK,SAAW,IAAI,eAAe,CACjC,MAAQC,GAAe,CACrB,KAAKP,GAA4BO,EACjCL,EAAiB,CACnB,CACF,CAAC,EAED,KAAK,SAAW,IAAI,eAAe,CACjC,MAAQK,GAAe,CACrB,KAAKN,GAA6BM,EAClCJ,EAAkB,CACpB,EACA,MAAQK,GAAY,CAClB,KAAK,YAAYA,CAAO,CAC1B,CACF,CAAC,CACH,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,KACb,CAEA,MAAM,KAAKA,EAAyB,CAClC,GAAI,CAAC,KAAKR,GACR,MAAM,IAAI,MAAM,iCAAiC,EAEnD,KAAKA,GAA0B,QAAQQ,CAAO,CAChD,CAEA,MAAM,OAAQ,CACZ,KAAKR,IAA2B,MAAM,IAAI,MAAM,mBAAmB,CAAC,EACpE,KAAKC,IAA4B,MAAM,IAAI,MAAM,mBAAmB,CAAC,EACrE,KAAK,UAAU,CACjB,CACF","names":["Server","CallToolRequestSchema","ListResourcesRequestSchema","ListResourceTemplatesRequestSchema","ListToolsRequestSchema","ReadResourceRequestSchema","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 type ListToolsResult,\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;\nexport type Annotations = NonNullable<\n ListToolsResult['tools'][number]['annotations']\n>;\n\nexport type Resource<Uri extends string = string, Result = unknown> = {\n uri: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(uri: `${Scheme}://${Uri}`): Promise<Result>;\n};\n\nexport type ResourceTemplate<Uri extends string = string, Result = unknown> = {\n uriTemplate: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(\n uri: `${Scheme}://${Uri}`,\n params: {\n [Param in ExtractParams<Uri>]: string;\n }\n ): Promise<Result>;\n};\n\nexport type Tool<\n Params extends z.ZodObject<any> = z.ZodObject<any>,\n Result = unknown,\n> = {\n description: string;\n annotations?: Annotations;\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 title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?: Prop<Record<string, Tool>>;\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer(options: McpServerOptions) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools() {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools()\n : options.tools;\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n ListResourcesRequestSchema,\n async (): Promise<ListResourcesResult> => {\n const allResources = await getResources();\n return {\n resources: allResources\n .filter((resource) => 'uri' in resource)\n .map(({ uri, name, description, mimeType }) => {\n return {\n uri,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n ListResourceTemplatesRequestSchema,\n async (): Promise<ListResourceTemplatesResult> => {\n const allResources = await getResources();\n return {\n resourceTemplates: allResources\n .filter((resource) => 'uriTemplate' in resource)\n .map(({ uriTemplate, name, description, mimeType }) => {\n return {\n uriTemplate,\n name,\n description,\n mimeType,\n };\n }),\n };\n }\n );\n\n server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request): Promise<ReadResourceResult> => {\n try {\n const allResources = await getResources();\n const { uri } = request.params;\n\n const resources = allResources.filter(\n (resource) => 'uri' in resource\n );\n const resource = resources.find((resource) =>\n compareUris(resource.uri, uri)\n );\n\n if (resource) {\n const result = await resource.read(uri as `${string}://${string}`);\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n }\n\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceTemplateUris = resourceTemplates.map(\n ({ uriTemplate }) => assertValidUri(uriTemplate)\n );\n\n const templateMatch = matchUriTemplate(uri, resourceTemplateUris);\n\n if (!templateMatch) {\n throw new Error('resource not found');\n }\n\n const resourceTemplate = resourceTemplates.find(\n (r) => r.uriTemplate === templateMatch.uri\n );\n\n if (!resourceTemplate) {\n throw new Error('resource not found');\n }\n\n const result = await resourceTemplate.read(\n uri as `${string}://${string}`,\n templateMatch.params\n );\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n } catch (error) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } as any;\n }\n }\n );\n }\n\n if (options.tools) {\n server.setRequestHandler(\n ListToolsRequestSchema,\n async (): Promise<ListToolsResult> => {\n const tools = await getTools();\n return {\n tools: Object.entries(tools).map(\n ([name, { description, annotations, parameters }]) => {\n const inputSchema = zodToJsonSchema(parameters);\n\n if (!('properties' in inputSchema)) {\n throw new Error('tool parameters must be a ZodObject');\n }\n\n return {\n name,\n description,\n annotations,\n inputSchema,\n };\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,MAQK,qCA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e,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","annotations","parameters","inputSchema","zodToJsonSchema","CallToolRequestSchema","toolName","args","newError","errorProps","prop","StreamTransport","#readableStreamController","#writeableStreamController","resolveReadReady","resolveWriteReady","readReady","resolve","writeReady","controller","message"]}
|
package/package.json
CHANGED
|
@@ -1,17 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supabase/mcp-utils",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "MCP utilities",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "dist/index.cjs",
|
|
8
8
|
"types": "dist/index.d.ts",
|
|
9
9
|
"sideEffects": false,
|
|
10
|
-
"scripts": {
|
|
11
|
-
"build": "tsup --clean",
|
|
12
|
-
"test": "vitest",
|
|
13
|
-
"prepublishOnly": "npm run build"
|
|
14
|
-
},
|
|
15
10
|
"files": [
|
|
16
11
|
"dist/**/*"
|
|
17
12
|
],
|
|
@@ -23,7 +18,7 @@
|
|
|
23
18
|
}
|
|
24
19
|
},
|
|
25
20
|
"dependencies": {
|
|
26
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
21
|
+
"@modelcontextprotocol/sdk": "^1.18.0",
|
|
27
22
|
"zod": "^3.24.1",
|
|
28
23
|
"zod-to-json-schema": "^3.24.1"
|
|
29
24
|
},
|
|
@@ -34,5 +29,13 @@
|
|
|
34
29
|
"tsup": "^8.3.5",
|
|
35
30
|
"typescript": "^5.6.3",
|
|
36
31
|
"vitest": "^2.1.9"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsup --clean",
|
|
35
|
+
"dev": "tsup --watch",
|
|
36
|
+
"typecheck": "tsc --noEmit",
|
|
37
|
+
"prebuild": "pnpm typecheck",
|
|
38
|
+
"test": "vitest",
|
|
39
|
+
"test:coverage": "vitest --coverage"
|
|
37
40
|
}
|
|
38
|
-
}
|
|
41
|
+
}
|