@schemarch/mcp-utils 0.0.0-stage → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +104 -2
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +236 -0
- package/dist/index.d.ts +236 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/package.json +44 -3
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 Schemarch
|
|
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/README.md
CHANGED
|
@@ -1,3 +1,105 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @schemarch/mcp-utils
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A collection of utilities for working with the Model Context Protocol (MCP).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```shell
|
|
8
|
+
npm i @schemarch/mcp-utils
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```shell
|
|
12
|
+
yarn add @schemarch/mcp-utils
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```shell
|
|
16
|
+
pnpm add @schemarch/mcp-utils
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The `StreamTransport` example below also needs `@modelcontextprotocol/client`, which is a separate
|
|
20
|
+
package from the `@modelcontextprotocol/server` peer dependency and is not installed for you:
|
|
21
|
+
|
|
22
|
+
```shell
|
|
23
|
+
npm i @modelcontextprotocol/client
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## API
|
|
27
|
+
|
|
28
|
+
### `StreamTransport`
|
|
29
|
+
|
|
30
|
+
If you're building an MCP client, you'll need to connect to MCP servers programmatically using a [transport](https://modelcontextprotocol.io/docs/concepts/transports).
|
|
31
|
+
|
|
32
|
+
In addition to MCP's [built-in](https://modelcontextprotocol.io/docs/concepts/transports#built-in-transport-types) transports, we also offer a `StreamTransport` to connect to clients with servers directly in-memory or over your own stream-based transport:
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { Client } from '@modelcontextprotocol/client';
|
|
36
|
+
import { StreamTransport } from '@schemarch/mcp-utils';
|
|
37
|
+
import { PostgrestMcpServer } from '@schemarch/mcp-server-postgrest';
|
|
38
|
+
|
|
39
|
+
// Create a stream transport for both client and server
|
|
40
|
+
const clientTransport = new StreamTransport();
|
|
41
|
+
const serverTransport = new StreamTransport();
|
|
42
|
+
|
|
43
|
+
// Connect the streams together
|
|
44
|
+
clientTransport.readable.pipeTo(serverTransport.writable);
|
|
45
|
+
serverTransport.readable.pipeTo(clientTransport.writable);
|
|
46
|
+
|
|
47
|
+
const client = new Client(
|
|
48
|
+
{
|
|
49
|
+
name: 'MyClient',
|
|
50
|
+
version: '0.1.0',
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
capabilities: {},
|
|
54
|
+
}
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
const server = new PostgrestMcpServer({
|
|
58
|
+
apiUrl: API_URL,
|
|
59
|
+
schema: 'public',
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// Connect the client and server to their respective transports
|
|
63
|
+
await server.connect(serverTransport);
|
|
64
|
+
await client.connect(clientTransport);
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
A `StreamTransport` implements a standard duplex stream interface via [`ReadableStream`](https://developer.mozilla.org/docs/Web/API/ReadableStream) and [`WritableStream`](https://developer.mozilla.org/docs/Web/API/WritableStream):
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
interface StreamTransport {
|
|
71
|
+
readable: ReadableStream;
|
|
72
|
+
writable: WritableStream;
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
You can use `pipeTo` or `pipeThrough` to connect or transform streams. For more information, see the [Web Streams API](https://developer.mozilla.org/docs/Web/API/Streams_API).
|
|
77
|
+
|
|
78
|
+
If your using Node.js streams, you can use their [`.toWeb()`](https://nodejs.org/api/stream.html#streamduplextowebstreamduplex) and [`.fromWeb()`](https://nodejs.org/api/stream.html#streamduplexfromwebpair-options) methods to convert to and from web standard streams.
|
|
79
|
+
|
|
80
|
+
The full interface for `StreamTransport` is as follows:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { JSONRPCMessage, Transport } from '@modelcontextprotocol/server';
|
|
84
|
+
|
|
85
|
+
interface DuplexStream<T> {
|
|
86
|
+
readable: ReadableStream<T>;
|
|
87
|
+
writable: WritableStream<T>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
declare class StreamTransport
|
|
91
|
+
implements Transport, DuplexStream<JSONRPCMessage>
|
|
92
|
+
{
|
|
93
|
+
ready: Promise<void>;
|
|
94
|
+
readable: ReadableStream<JSONRPCMessage>;
|
|
95
|
+
writable: WritableStream<JSONRPCMessage>;
|
|
96
|
+
onclose?: () => void;
|
|
97
|
+
onerror?: (error: Error) => void;
|
|
98
|
+
onmessage?: (message: JSONRPCMessage) => void;
|
|
99
|
+
|
|
100
|
+
constructor();
|
|
101
|
+
start(): Promise<void>;
|
|
102
|
+
send(message: JSONRPCMessage): Promise<void>;
|
|
103
|
+
close(): Promise<void>;
|
|
104
|
+
}
|
|
105
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _server = require('@modelcontextprotocol/server');var _v4 = require('zod/v4');function g(e){try{return new URL(e),e}catch (e2){throw new Error(`invalid uri: ${e}`)}}function O(e,t){let n=new URL(e),r=new URL(t);return n.href===r.href}function w(e,t){let r=new URL(e).pathname.split("/").slice(1);for(let m of t){let l=new URL(m),s=decodeURIComponent(l.pathname).split("/").slice(1);if(r.length!==s.length)continue;let o={},i=!0;for(let c=0;c<r.length;c++){let a=s[c],d=r[c];if(!a||!d)break;if(a.startsWith("{")&&a.endsWith("}")){let p=a.slice(1,-1);if(!p)break;o[p]=d}else if(r[c]!==s[c]){i=!1;break}}if(i)return{uri:m,params:o}}}function x(e,t){if(!e)return;let n=performance.now(),r;try{if(r=e(t),r&&"then"in r&&typeof r.then=="function"){Promise.resolve(r).catch(()=>{});return}}catch (e3){return}if(!r)return;let m=!1,l="completed";return{tool:{record(s){m||S(()=>r.record(s))},setOutcome(s){m||(l=s)}},end(s){if(m)return;m=!0;let o=performance.now()-n;S(()=>r.end({result:s,durationMs:o}))},outcome:()=>l}}function S(e){try{Promise.resolve(e()).catch(()=>{})}catch (e4){}}function I(e,t){return{uri:e,...t}}function B(e,t){return{uriTemplate:e,...t}}function L(e,t){return{uri:e,mimeType:"application/json",...t}}function N(e,t){return{uriTemplate:e,mimeType:"application/json",...t}}function Z(e,t){return t.map(n=>{if("uri"in n){let l=new URL(n.uri,`${e}://`),s=decodeURI(l.href);return{...n,uri:s}}let r=new URL(n.uriTemplate,`${e}://`),m=decodeURI(r.href);return{...n,uriTemplate:m}})}function J(e,t){return{uri:e,mimeType:"application/json",text:JSON.stringify(t)}}function _(e){return e}function A(e){let t={};e.resources&&(t.resources={}),e.tools&&(t.tools={});let n=new (0, _server.Server)({name:e.name,title:e.title,version:e.version},{capabilities:t,instructions:e.instructions,requestState:e.requestState});async function r(){if(!e.resources)throw new Error("resources not available");return typeof e.resources=="function"?await e.resources():e.resources}async function m(s){if(!e.tools)throw new Error("tools not available");return typeof e.tools=="function"?await e.tools(s):e.tools}async function l(s,o){let i=x(e.observer,{method:s}),c="handler_error";try{let a=await o();return c="isError"in a&&a.isError===!0?"tool_error":"completed",a}finally{_optionalChain([i, 'optionalAccess', _2 => _2.end, 'call', _3 => _3(c)])}}return n.oninitialized=async()=>{let s=n.getClientVersion(),o=n.getClientCapabilities();if(!s)throw new Error("client info not available after initialization");if(!o)throw new Error("client capabilities not available after initialization");let i={clientInfo:s,clientCapabilities:o};await _optionalChain([e, 'access', _4 => _4.onInitialize, 'optionalCall', _5 => _5(i)])},e.resources&&(n.setRequestHandler("resources/list",()=>l("resources/list",async()=>({resources:(await r()).filter(o=>"uri"in o).map(({uri:o,name:i,description:c,mimeType:a})=>({uri:o,name:i,description:c,mimeType:a}))}))),n.setRequestHandler("resources/templates/list",()=>l("resources/templates/list",async()=>({resourceTemplates:(await r()).filter(o=>"uriTemplate"in o).map(({uriTemplate:o,name:i,description:c,mimeType:a})=>({uriTemplate:o,name:i,description:c,mimeType:a}))}))),n.setRequestHandler("resources/read",s=>l("resources/read",async()=>{try{let o=await r(),{uri:i}=s.params,a=o.filter(u=>"uri"in u).find(u=>O(u.uri,i));if(a){let u=await a.read(i);return{contents:Array.isArray(u)?u:[u]}}let d=o.filter(u=>"uriTemplate"in u),p=d.map(({uriTemplate:u})=>g(u)),f=w(i,p);if(!f)throw new Error("resource not found");let y=d.find(u=>u.uriTemplate===f.uri);if(!y)throw new Error("resource not found");let v=await y.read(i,f.params);return{contents:Array.isArray(v)?v:[v]}}catch(o){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:C(o)})}]}}}))),e.tools&&(n.setRequestHandler("tools/list",(s,o)=>l("tools/list",async()=>{let i=await m(o);return{tools:await Promise.all(Object.entries(i).filter(([,c])=>!c.hidden).map(async([c,{description:a,annotations:d,parameters:p}])=>{let f=_v4.z.toJSONSchema(p,{target:"draft-7"});return{name:c,description:typeof a=="function"?await a():a,annotations:d,inputSchema:f}}))}})),n.setRequestHandler("tools/call",async(s,o)=>{let i=s.params.name,c="other";if(e.observer)try{c=_nullishCoalesce(_optionalChain([e, 'access', _6 => _6.classifyTool, 'optionalCall', _7 => _7(i)]), () => ("other"))}catch (e5){}let a=x(e.observer,{method:"tools/call",tool:c}),d="handler_error";try{let p=await m(o);if(!(i in p))throw new Error("tool not found");let f=p[i];if(!f)throw new Error("tool not found");let y=f.parameters.strict().parse(_nullishCoalesce(s.params.arguments, () => ({}))),R=await(async h=>{let T=await h.execute(y,o,_optionalChain([a, 'optionalAccess', _8 => _8.tool])).then(b=>({success:!0,data:b})).catch(b=>({success:!1,error:b}));try{_optionalChain([e, 'access', _9 => _9.onToolCall, 'optionalCall', _10 => _10({name:i,arguments:y,annotations:h.annotations,...T})])}catch(b){console.error("Failed to run tool callback",b)}if(!T.success)throw T.error;return T.data})(f);if(j(R))return d="input_required",R;if(_server.isCallToolResult.call(void 0, R))return d=R.isError?"tool_error":_nullishCoalesce(_optionalChain([a, 'optionalAccess', _11 => _11.outcome, 'call', _12 => _12()]), () => ("completed")),R;let u=R!=null?[{type:"text",text:JSON.stringify(R)}]:[];return d=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _13 => _13.outcome, 'call', _14 => _14()]), () => ("completed")),{content:u}}catch(p){let f={isError:!0,content:[{type:"text",text:JSON.stringify({error:C(p)})}]};return d="tool_error",f}finally{_optionalChain([a, 'optionalAccess', _15 => _15.end, 'call', _16 => _16(d)])}})),n}function j(e){return typeof e=="object"&&e!==null&&e.resultType==="input_required"}function C(e){if(!e||typeof e!="object")return e;let t={},n=["name","message"];for(let r of n)r in e&&(t[r]=e[r]);return t}var P=class{#e;#t;constructor(){let t,n,r=new Promise(l=>{t=l}),m=new Promise(l=>{n=l});this.ready=Promise.all([r,m]).then(()=>{}),this.readable=new ReadableStream({start:l=>{this.#e=l,t()}}),this.writable=new WritableStream({start:l=>{this.#t=l,n()},write:l=>{_optionalChain([this, 'access', _17 => _17.onmessage, 'optionalCall', _18 => _18(l)])}})}async start(){await this.ready}async send(t){if(!this.#e)throw new Error("readable stream not initialized");this.#e.enqueue(t)}async close(){_optionalChain([this, 'access', _19 => _19.#e, 'optionalAccess', _20 => _20.error, 'call', _21 => _21(new Error("connection closed"))]),_optionalChain([this, 'access', _22 => _22.#t, 'optionalAccess', _23 => _23.error, 'call', _24 => _24(new Error("connection closed"))]),_optionalChain([this, 'access', _25 => _25.onclose, 'optionalCall', _26 => _26()])}};exports.StreamTransport = P; exports.createMcpServer = A; exports.jsonResource = L; exports.jsonResourceResponse = J; exports.jsonResourceTemplate = N; exports.resource = I; exports.resourceTemplate = B; exports.resources = Z; exports.tool = _;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/util.ts"],"names":["assertValidUri","uri"],"mappings":"AAAA,uuBAAyC,4BAcvB,SCTFA,CAAAA,CAAeC,CAAAA,CAAa,CAC1C,GAAI,CACF,OAAA,IAAI,GAAA,CAAIA,CAAG,CAAA,CACJA,CACT,CAAA,UAAQ,CACN,MAAM,IAAI,KAAA,CAAM,CAAA,aAAA,EAAgBA,CAAG,CAAA,CAAA","file":"/home/copilot/dev/schemarch-rebuild/mcp/packages/mcp-utils/dist/index.cjs","sourcesContent":["import { isCallToolResult, Server } from '@modelcontextprotocol/server';\nimport type {\n CallToolResult,\n ClientCapabilities,\n Implementation,\n InputRequiredResult,\n ListResourcesResult,\n ListResourceTemplatesResult,\n ListToolsResult,\n Tool as McpTool,\n ReadResourceResult,\n ServerCapabilities,\n ServerContext,\n} from '@modelcontextprotocol/server';\nimport { z } from 'zod/v4';\n\nimport type { ExtractParams } from './types.js';\nimport { assertValidUri, compareUris, matchUriTemplate } from './util.js';\nimport { beginObservation } from './observation.js';\nimport type {\n ObservationEnd,\n ObservedMethod,\n ToolObservation,\n RequestObserver,\n} from './observation.js';\n\nexport type Scheme = string;\nexport type Annotations = NonNullable<\n ListToolsResult['tools'][number]['annotations']\n>;\n\nexport type Resource<Uri extends string = string, Result = unknown> = {\n uri: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(uri: `${Scheme}://${Uri}`): Promise<Result>;\n};\n\nexport type ResourceTemplate<Uri extends string = string, Result = unknown> = {\n uriTemplate: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(\n uri: `${Scheme}://${Uri}`,\n params: {\n [Param in ExtractParams<Uri>]: string;\n }\n ): Promise<Result>;\n};\n\nexport type Tool<\n Params extends z.ZodObject<any> = z.ZodObject<any>,\n // MCP spec restricts outputSchema to type \"object\" at the root level:\n // https://modelcontextprotocol.io/specification/2025-11-25/schema#tool-outputschema\n OutputSchema extends z.ZodObject<any> = z.ZodObject<any>,\n Fact = never,\n> = {\n description: Prop<string>;\n annotations?: Annotations;\n parameters: Params;\n outputSchema: OutputSchema;\n /** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */\n hidden?: boolean;\n /**\n * Executes the tool. `ctx` is the SDK's per-request `ServerContext`\n * (elicitation, multi-round-trip `requestState`, HTTP info, etc.) — most\n * tools ignore it.\n *\n * Returning an `InputRequiredResult` or a direct `CallToolResult` is\n * passed straight to the client instead of being JSON-wrapped; any other\n * value is wrapped as today (`{ content: [{ type: 'text', text:\n * JSON.stringify(value) }] }`).\n *\n * The optional observation handle records custom facts and sets an explicit\n * outcome. Its methods isolate sink failures and become inert after settlement.\n */\n execute: (\n params: z.infer<Params>,\n ctx: ServerContext,\n observation?: ToolObservation<Fact>\n ) => Promise<z.infer<OutputSchema> | InputRequiredResult | CallToolResult>;\n};\n\n/**\n * Helper function to define an MCP resource while preserving type information.\n */\nexport function resource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri'>\n): Resource<Uri, Result> {\n return {\n uri,\n ...resource,\n };\n}\n\n/**\n * Helper function to define an MCP resource with a URI template while preserving type information.\n */\nexport function resourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource while preserving type information.\n */\nexport function jsonResource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>\n): Resource<Uri, Result> {\n return {\n uri,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource with a URI template while preserving type information.\n */\nexport function jsonResourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a list of resources that share a common URI scheme.\n */\nexport function resources<Scheme extends string>(\n scheme: Scheme,\n resources: (Resource | ResourceTemplate)[]\n): (\n | Resource<`${Scheme}://${string}`>\n | ResourceTemplate<`${Scheme}://${string}`>\n)[] {\n return resources.map((resource) => {\n if ('uri' in resource) {\n const url = new URL(resource.uri, `${scheme}://`);\n const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`;\n\n return {\n ...resource,\n uri,\n };\n }\n\n const url = new URL(resource.uriTemplate, `${scheme}://`);\n const uriTemplate = decodeURI(\n url.href\n ) as `${Scheme}://${typeof resource.uriTemplate}`;\n\n return {\n ...resource,\n uriTemplate,\n };\n });\n}\n\n/**\n * Helper function to create a JSON resource response.\n */\nexport function jsonResourceResponse<Uri extends string, Response>(\n uri: Uri,\n response: Response\n) {\n return {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(response),\n };\n}\n\n/**\n * Helper function to define an MCP tool while preserving type information.\n */\nexport function tool<\n Params extends z.ZodObject<any>,\n OutputSchema extends z.ZodObject<any>,\n Fact = never,\n>(tool: Tool<Params, OutputSchema, Fact>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n name: string;\n arguments: Record<string, unknown>;\n annotations?: Annotations;\n};\n\ntype ToolCallSuccessDetails = ToolCallBaseDetails & {\n success: true;\n data: unknown;\n};\n\ntype ToolCallErrorDetails = ToolCallBaseDetails & {\n success: false;\n error: unknown;\n};\n\nexport type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;\n\nexport type InitCallback = (initData: InitData) => void | Promise<void>;\nexport type ToolCallCallback = (details: ToolCallDetails) => void;\nexport type PropCallback<T> = () => T | Promise<T>;\nexport type Prop<T> = T | PropCallback<T>;\n\nexport type McpServerOptions<Bucket extends string = never, Fact = never> = {\n /**\n * The name of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n name: string;\n\n /**\n * The title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Optional instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions?: string;\n\n /**\n * Callback for after a tool is called.\n */\n onToolCall?: ToolCallCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?:\n | Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n | ((\n ctx?: ServerContext\n ) =>\n | Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n | Promise<\n Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n >);\n\n /**\n * Multi-round-trip `requestState` integrity hook (protocol revision\n * 2026-07-28), passed straight through to the underlying SDK `Server`.\n *\n * Configure this with `createRequestStateCodec`'s `verify` to\n * authenticate `requestState` a tool mints via `inputRequired(...)`.\n * Leaving it unset keeps the SDK's passthrough behavior.\n */\n requestState?: {\n verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;\n };\n\n /** Optional per-request observer; see ObservedMethod for covered handlers. */\n observer?: RequestObserver<Bucket, Fact>;\n classifyTool?: (name: string) => Bucket | 'other';\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer<Bucket extends string = never, Fact = never>(\n options: McpServerOptions<Bucket, Fact>\n) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n instructions: options.instructions,\n requestState: options.requestState,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools(ctx?: ServerContext) {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools(ctx)\n : options.tools;\n }\n\n async function observed<Result extends object>(\n method: Exclude<ObservedMethod, 'tools/call'>,\n run: () => Promise<Result>\n ): Promise<Result> {\n const scope = beginObservation(options.observer, { method });\n let outcome: ObservationEnd['result'] = 'handler_error';\n try {\n const result = await run();\n outcome =\n 'isError' in result && result.isError === true\n ? 'tool_error'\n : 'completed';\n return result;\n } finally {\n scope?.end(outcome);\n }\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n 'resources/list',\n (): Promise<ListResourcesResult> =>\n observed('resources/list', async () => {\n const allResources = await getResources();\n return {\n resources: allResources\n .filter((resource) => 'uri' in resource)\n .map(({ uri, name, description, mimeType }) => {\n return {\n uri,\n name,\n description,\n mimeType,\n };\n }),\n };\n })\n );\n\n server.setRequestHandler(\n 'resources/templates/list',\n (): Promise<ListResourceTemplatesResult> =>\n observed('resources/templates/list', async () => {\n const allResources = await getResources();\n return {\n resourceTemplates: allResources\n .filter((resource) => 'uriTemplate' in resource)\n .map(({ uriTemplate, name, description, mimeType }) => {\n return {\n uriTemplate,\n name,\n description,\n mimeType,\n };\n }),\n };\n })\n );\n\n server.setRequestHandler(\n 'resources/read',\n (request): Promise<ReadResourceResult> =>\n observed('resources/read', async () => {\n try {\n const allResources = await getResources();\n const { uri } = request.params;\n\n const resources = allResources.filter(\n (resource) => 'uri' in resource\n );\n const resource = resources.find((resource) =>\n compareUris(resource.uri, uri)\n );\n\n if (resource) {\n const result = await resource.read(\n uri as `${string}://${string}`\n );\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n }\n\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceTemplateUris = resourceTemplates.map(\n ({ uriTemplate }) => assertValidUri(uriTemplate)\n );\n\n const templateMatch = matchUriTemplate(uri, resourceTemplateUris);\n\n if (!templateMatch) {\n throw new Error('resource not found');\n }\n\n const resourceTemplate = resourceTemplates.find(\n (r) => r.uriTemplate === templateMatch.uri\n );\n\n if (!resourceTemplate) {\n throw new Error('resource not found');\n }\n\n const result = await resourceTemplate.read(\n uri as `${string}://${string}`,\n templateMatch.params\n );\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n } catch (error) {\n // Preserve the existing resource error payload despite the SDK result type.\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } as unknown as ReadResourceResult;\n }\n })\n );\n }\n\n if (options.tools) {\n server.setRequestHandler(\n 'tools/list',\n (_request, ctx): Promise<ListToolsResult> =>\n observed('tools/list', async () => {\n const tools = await getTools(ctx);\n\n return {\n tools: await Promise.all(\n Object.entries(tools)\n .filter(([, tool]) => !tool.hidden)\n .map(\n async ([name, { description, annotations, parameters }]) => {\n const inputSchema = z.toJSONSchema(parameters, {\n target: 'draft-7',\n });\n\n return {\n name,\n description:\n typeof description === 'function'\n ? await description()\n : description,\n annotations,\n // Casting the same as the SDK does:\n // https://github.com/modelcontextprotocol/typescript-sdk/blob/fb07af810b51003c338dc4885a9e42f54519f9af/src/server/mcp.ts#L154\n inputSchema: inputSchema as McpTool['inputSchema'],\n };\n }\n )\n ),\n } satisfies ListToolsResult;\n })\n );\n\n server.setRequestHandler('tools/call', async (request, ctx) => {\n const toolName = request.params.name;\n let tool: Bucket | 'other' = 'other';\n if (options.observer) {\n try {\n tool = options.classifyTool?.(toolName) ?? 'other';\n } catch {}\n }\n const scope = beginObservation(options.observer, {\n method: 'tools/call',\n tool,\n });\n let outcome: ObservationEnd['result'] = 'handler_error';\n\n try {\n const tools = await getTools(ctx);\n\n if (!(toolName in tools)) {\n throw new Error('tool not found');\n }\n\n const tool = tools[toolName];\n\n if (!tool) {\n throw new Error('tool not found');\n }\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const executeWithCallback = async (\n tool: Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>\n ) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args, ctx, scope?.tool)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n try {\n options.onToolCall?.({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\n });\n } catch (error) {\n // Don't fail the tool call if the callback fails\n console.error('Failed to run tool callback', error);\n }\n\n // Unwrap result\n if (!res.success) {\n throw res.error;\n }\n return res.data;\n };\n\n const result = await executeWithCallback(tool);\n\n // An InputRequiredResult is already shaped for the wire.\n if (isInputRequiredResult(result)) {\n outcome = 'input_required';\n return result;\n }\n\n // A direct CallToolResult is already shaped for the wire; pass it\n // through instead of JSON-wrapping it.\n if (isCallToolResult(result)) {\n outcome = result.isError\n ? 'tool_error'\n : (scope?.outcome() ?? 'completed');\n return result;\n }\n\n const content =\n result != null\n ? [{ type: 'text' as const, text: JSON.stringify(result) }]\n : [];\n\n outcome = scope?.outcome() ?? 'completed';\n return {\n content,\n };\n } catch (error) {\n const result = {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } satisfies CallToolResult;\n outcome = 'tool_error';\n return result;\n } finally {\n scope?.end(outcome);\n }\n });\n }\n\n return server;\n}\n\nfunction isInputRequiredResult(value: unknown): value is InputRequiredResult {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { resultType?: unknown }).resultType === 'input_required'\n );\n}\n\nfunction enumerateError(error: unknown) {\n if (!error) {\n return error;\n }\n\n if (typeof error !== 'object') {\n return error;\n }\n\n const newError: Record<string, unknown> = {};\n\n const errorProps = ['name', 'message'] as const;\n\n for (const prop of errorProps) {\n if (prop in error) {\n newError[prop] = (error as Record<string, unknown>)[prop];\n }\n }\n\n return newError;\n}\n","import type { ExtractParams } from './types.js';\n\n/**\n * Asserts that a URI is valid.\n */\nexport function assertValidUri(uri: string) {\n try {\n new URL(uri);\n return uri;\n } catch {\n throw new Error(`invalid uri: ${uri}`);\n }\n}\n\n/**\n * Compares two URIs.\n */\nexport function compareUris(uriA: string, uriB: string): boolean {\n const urlA = new URL(uriA);\n const urlB = new URL(uriB);\n\n return urlA.href === urlB.href;\n}\n\n/**\n * Matches a URI to a RFC 6570 URI Template (resourceUris) and extracts\n * the parameters.\n *\n * Currently only supports simple string parameters.\n */\nexport function matchUriTemplate<Templates extends string[]>(\n uri: string,\n uriTemplates: Templates\n):\n | {\n uri: Templates[number];\n params: { [Param in ExtractParams<Templates[number]>]: string };\n }\n | undefined {\n const url = new URL(uri);\n const segments = url.pathname.split('/').slice(1);\n\n for (const resourceUri of uriTemplates) {\n const resourceUrl = new URL(resourceUri);\n const resourceSegments = decodeURIComponent(resourceUrl.pathname)\n .split('/')\n .slice(1);\n\n if (segments.length !== resourceSegments.length) {\n continue;\n }\n\n const params: Record<string, string> = {};\n let isMatch = true;\n\n for (let i = 0; i < segments.length; i++) {\n const resourceSegment = resourceSegments[i];\n const segment = segments[i];\n\n if (!resourceSegment || !segment) {\n break;\n }\n\n if (resourceSegment.startsWith('{') && resourceSegment.endsWith('}')) {\n const paramKey = resourceSegment.slice(1, -1);\n\n if (!paramKey) {\n break;\n }\n\n params[paramKey] = segment;\n } else if (segments[i] !== resourceSegments[i]) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n return {\n uri: resourceUri,\n params: params as {\n [Param in ExtractParams<Templates[number]>]: string;\n },\n };\n }\n }\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { ListToolsResult, ServerContext, InputRequiredResult, CallToolResult, Implementation, ClientCapabilities, Server, Transport, JSONRPCMessage } from '@modelcontextprotocol/server';
|
|
2
|
+
import { z } from 'zod/v4';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A web stream that can be both read from and written to.
|
|
6
|
+
*/
|
|
7
|
+
interface DuplexStream<T> {
|
|
8
|
+
readable: ReadableStream<T>;
|
|
9
|
+
writable: WritableStream<T>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Extracts parameter names from a string path.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* type Path = '/schemas/{schema}/tables/{table}';
|
|
16
|
+
* type Params = ExtractParams<Path>; // 'schema' | 'table'
|
|
17
|
+
*/
|
|
18
|
+
type ExtractParams<Path extends string> = Path extends `${string}{${infer P}}${infer Rest}` ? P | ExtractParams<Rest> : never;
|
|
19
|
+
|
|
20
|
+
/** Observations describe handler attempts, not transport delivery or backend commit. */
|
|
21
|
+
type ObservedMethod = 'tools/call' | 'tools/list' | 'resources/list' | 'resources/templates/list' | 'resources/read';
|
|
22
|
+
type ObservationContext<Bucket extends string = never> = Readonly<{
|
|
23
|
+
method: 'tools/call';
|
|
24
|
+
tool: Bucket | 'other';
|
|
25
|
+
}> | Readonly<{
|
|
26
|
+
method: Exclude<ObservedMethod, 'tools/call'>;
|
|
27
|
+
}>;
|
|
28
|
+
type ToolOutcome = 'completed' | 'declined' | 'cancelled';
|
|
29
|
+
type ToolObservation<Fact = never> = Readonly<{
|
|
30
|
+
record: (fact: Fact) => void;
|
|
31
|
+
setOutcome: (result: ToolOutcome) => void;
|
|
32
|
+
}>;
|
|
33
|
+
type ObservationEnd = Readonly<{
|
|
34
|
+
result: ToolOutcome | 'input_required' | 'tool_error' | 'handler_error';
|
|
35
|
+
durationMs: number;
|
|
36
|
+
}>;
|
|
37
|
+
/** Sink failures are isolated; custom facts remain the producer's responsibility. */
|
|
38
|
+
type RequestObservation<Fact = never> = Readonly<{
|
|
39
|
+
record: (fact: Fact) => void | Promise<void>;
|
|
40
|
+
end: (result: ObservationEnd) => void | Promise<void>;
|
|
41
|
+
}>;
|
|
42
|
+
/** Synchronous factory; promises and thenables are unsupported. */
|
|
43
|
+
type RequestObserver<Bucket extends string = never, Fact = never> = (context: ObservationContext<Bucket>) => RequestObservation<Fact> | undefined;
|
|
44
|
+
|
|
45
|
+
type Scheme = string;
|
|
46
|
+
type Annotations = NonNullable<ListToolsResult['tools'][number]['annotations']>;
|
|
47
|
+
type Resource<Uri extends string = string, Result = unknown> = {
|
|
48
|
+
uri: Uri;
|
|
49
|
+
name: string;
|
|
50
|
+
description?: string;
|
|
51
|
+
mimeType?: string;
|
|
52
|
+
read(uri: `${Scheme}://${Uri}`): Promise<Result>;
|
|
53
|
+
};
|
|
54
|
+
type ResourceTemplate<Uri extends string = string, Result = unknown> = {
|
|
55
|
+
uriTemplate: Uri;
|
|
56
|
+
name: string;
|
|
57
|
+
description?: string;
|
|
58
|
+
mimeType?: string;
|
|
59
|
+
read(uri: `${Scheme}://${Uri}`, params: {
|
|
60
|
+
[Param in ExtractParams<Uri>]: string;
|
|
61
|
+
}): Promise<Result>;
|
|
62
|
+
};
|
|
63
|
+
type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema extends z.ZodObject<any> = z.ZodObject<any>, Fact = never> = {
|
|
64
|
+
description: Prop<string>;
|
|
65
|
+
annotations?: Annotations;
|
|
66
|
+
parameters: Params;
|
|
67
|
+
outputSchema: OutputSchema;
|
|
68
|
+
/** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */
|
|
69
|
+
hidden?: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Executes the tool. `ctx` is the SDK's per-request `ServerContext`
|
|
72
|
+
* (elicitation, multi-round-trip `requestState`, HTTP info, etc.) — most
|
|
73
|
+
* tools ignore it.
|
|
74
|
+
*
|
|
75
|
+
* Returning an `InputRequiredResult` or a direct `CallToolResult` is
|
|
76
|
+
* passed straight to the client instead of being JSON-wrapped; any other
|
|
77
|
+
* value is wrapped as today (`{ content: [{ type: 'text', text:
|
|
78
|
+
* JSON.stringify(value) }] }`).
|
|
79
|
+
*
|
|
80
|
+
* The optional observation handle records custom facts and sets an explicit
|
|
81
|
+
* outcome. Its methods isolate sink failures and become inert after settlement.
|
|
82
|
+
*/
|
|
83
|
+
execute: (params: z.infer<Params>, ctx: ServerContext, observation?: ToolObservation<Fact>) => Promise<z.infer<OutputSchema> | InputRequiredResult | CallToolResult>;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Helper function to define an MCP resource while preserving type information.
|
|
87
|
+
*/
|
|
88
|
+
declare function resource<Uri extends string, Result>(uri: Uri, resource: Omit<Resource<Uri, Result>, 'uri'>): Resource<Uri, Result>;
|
|
89
|
+
/**
|
|
90
|
+
* Helper function to define an MCP resource with a URI template while preserving type information.
|
|
91
|
+
*/
|
|
92
|
+
declare function resourceTemplate<Uri extends string, Result>(uriTemplate: Uri, resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>): ResourceTemplate<Uri, Result>;
|
|
93
|
+
/**
|
|
94
|
+
* Helper function to define a JSON resource while preserving type information.
|
|
95
|
+
*/
|
|
96
|
+
declare function jsonResource<Uri extends string, Result>(uri: Uri, resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>): Resource<Uri, Result>;
|
|
97
|
+
/**
|
|
98
|
+
* Helper function to define a JSON resource with a URI template while preserving type information.
|
|
99
|
+
*/
|
|
100
|
+
declare function jsonResourceTemplate<Uri extends string, Result>(uriTemplate: Uri, resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>): ResourceTemplate<Uri, Result>;
|
|
101
|
+
/**
|
|
102
|
+
* Helper function to define a list of resources that share a common URI scheme.
|
|
103
|
+
*/
|
|
104
|
+
declare function resources<Scheme extends string>(scheme: Scheme, resources: (Resource | ResourceTemplate)[]): (Resource<`${Scheme}://${string}`> | ResourceTemplate<`${Scheme}://${string}`>)[];
|
|
105
|
+
/**
|
|
106
|
+
* Helper function to create a JSON resource response.
|
|
107
|
+
*/
|
|
108
|
+
declare function jsonResourceResponse<Uri extends string, Response>(uri: Uri, response: Response): {
|
|
109
|
+
uri: Uri;
|
|
110
|
+
mimeType: string;
|
|
111
|
+
text: string;
|
|
112
|
+
};
|
|
113
|
+
/**
|
|
114
|
+
* Helper function to define an MCP tool while preserving type information.
|
|
115
|
+
*/
|
|
116
|
+
declare function tool<Params extends z.ZodObject<any>, OutputSchema extends z.ZodObject<any>, Fact = never>(tool: Tool<Params, OutputSchema, Fact>): Tool<Params, OutputSchema, Fact>;
|
|
117
|
+
type InitData = {
|
|
118
|
+
clientInfo: Implementation;
|
|
119
|
+
clientCapabilities: ClientCapabilities;
|
|
120
|
+
};
|
|
121
|
+
type ToolCallBaseDetails = {
|
|
122
|
+
name: string;
|
|
123
|
+
arguments: Record<string, unknown>;
|
|
124
|
+
annotations?: Annotations;
|
|
125
|
+
};
|
|
126
|
+
type ToolCallSuccessDetails = ToolCallBaseDetails & {
|
|
127
|
+
success: true;
|
|
128
|
+
data: unknown;
|
|
129
|
+
};
|
|
130
|
+
type ToolCallErrorDetails = ToolCallBaseDetails & {
|
|
131
|
+
success: false;
|
|
132
|
+
error: unknown;
|
|
133
|
+
};
|
|
134
|
+
type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;
|
|
135
|
+
type InitCallback = (initData: InitData) => void | Promise<void>;
|
|
136
|
+
type ToolCallCallback = (details: ToolCallDetails) => void;
|
|
137
|
+
type PropCallback<T> = () => T | Promise<T>;
|
|
138
|
+
type Prop<T> = T | PropCallback<T>;
|
|
139
|
+
type McpServerOptions<Bucket extends string = never, Fact = never> = {
|
|
140
|
+
/**
|
|
141
|
+
* The name of the MCP server. This will be sent to the client as part of
|
|
142
|
+
* the initialization process.
|
|
143
|
+
*/
|
|
144
|
+
name: string;
|
|
145
|
+
/**
|
|
146
|
+
* The title of the MCP server. This is a human-readable name that can be
|
|
147
|
+
* displayed in the client UI.
|
|
148
|
+
*
|
|
149
|
+
* If not provided, the name will be used as the title.
|
|
150
|
+
*/
|
|
151
|
+
title?: string;
|
|
152
|
+
/**
|
|
153
|
+
* The version of the MCP server. This will be sent to the client as part of
|
|
154
|
+
* the initialization process.
|
|
155
|
+
*/
|
|
156
|
+
version: string;
|
|
157
|
+
/**
|
|
158
|
+
* Callback for when initialization has fully completed with the client.
|
|
159
|
+
*/
|
|
160
|
+
onInitialize?: InitCallback;
|
|
161
|
+
/**
|
|
162
|
+
* Optional instructions describing how to use the server and its features.
|
|
163
|
+
*
|
|
164
|
+
* This can be used by clients to improve the LLM's understanding of available
|
|
165
|
+
* tools, resources, etc. It can be thought of like a "hint" to the model.
|
|
166
|
+
* For example, this information MAY be added to the system prompt.
|
|
167
|
+
*/
|
|
168
|
+
instructions?: string;
|
|
169
|
+
/**
|
|
170
|
+
* Callback for after a tool is called.
|
|
171
|
+
*/
|
|
172
|
+
onToolCall?: ToolCallCallback;
|
|
173
|
+
/**
|
|
174
|
+
* Resources to be served by the server. These can be defined as a static
|
|
175
|
+
* object or as a function that dynamically returns the object synchronously
|
|
176
|
+
* or asynchronously.
|
|
177
|
+
*
|
|
178
|
+
* If defined as a function, the function will be called whenever the client
|
|
179
|
+
* asks for the list of resources or reads a resource. This allows for dynamic
|
|
180
|
+
* resources that can change after the server has started.
|
|
181
|
+
*/
|
|
182
|
+
resources?: Prop<(Resource<string, unknown> | ResourceTemplate<string, unknown>)[]>;
|
|
183
|
+
/**
|
|
184
|
+
* Tools to be served by the server. These can be defined as a static object
|
|
185
|
+
* or as a function that dynamically returns the object synchronously or
|
|
186
|
+
* asynchronously.
|
|
187
|
+
*
|
|
188
|
+
* If defined as a function, the function will be called whenever the client
|
|
189
|
+
* asks for the list of tools or invokes a tool. This allows for dynamic tools
|
|
190
|
+
* that can change after the server has started.
|
|
191
|
+
*/
|
|
192
|
+
tools?: Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>> | ((ctx?: ServerContext) => Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>> | Promise<Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>>);
|
|
193
|
+
/**
|
|
194
|
+
* Multi-round-trip `requestState` integrity hook (protocol revision
|
|
195
|
+
* 2026-07-28), passed straight through to the underlying SDK `Server`.
|
|
196
|
+
*
|
|
197
|
+
* Configure this with `createRequestStateCodec`'s `verify` to
|
|
198
|
+
* authenticate `requestState` a tool mints via `inputRequired(...)`.
|
|
199
|
+
* Leaving it unset keeps the SDK's passthrough behavior.
|
|
200
|
+
*/
|
|
201
|
+
requestState?: {
|
|
202
|
+
verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;
|
|
203
|
+
};
|
|
204
|
+
/** Optional per-request observer; see ObservedMethod for covered handlers. */
|
|
205
|
+
observer?: RequestObserver<Bucket, Fact>;
|
|
206
|
+
classifyTool?: (name: string) => Bucket | 'other';
|
|
207
|
+
};
|
|
208
|
+
/**
|
|
209
|
+
* Creates an MCP server with the given options.
|
|
210
|
+
*
|
|
211
|
+
* Simplifies the process of creating an MCP server by providing a high-level
|
|
212
|
+
* API for defining resources and tools.
|
|
213
|
+
*/
|
|
214
|
+
declare function createMcpServer<Bucket extends string = never, Fact = never>(options: McpServerOptions<Bucket, Fact>): Server;
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* An MCP transport built on top of a duplex stream.
|
|
218
|
+
* It uses a `ReadableStream` to receive messages and a `WritableStream` to send messages.
|
|
219
|
+
*
|
|
220
|
+
* Useful if you wish to pipe messages over your own stream-based transport or directly between two streams.
|
|
221
|
+
*/
|
|
222
|
+
declare class StreamTransport implements Transport, DuplexStream<JSONRPCMessage> {
|
|
223
|
+
#private;
|
|
224
|
+
ready: Promise<void>;
|
|
225
|
+
readable: ReadableStream<JSONRPCMessage>;
|
|
226
|
+
writable: WritableStream<JSONRPCMessage>;
|
|
227
|
+
onclose?: () => void;
|
|
228
|
+
onerror?: (error: Error) => void;
|
|
229
|
+
onmessage?: (message: JSONRPCMessage) => void;
|
|
230
|
+
constructor();
|
|
231
|
+
start(): Promise<void>;
|
|
232
|
+
send(message: JSONRPCMessage): Promise<void>;
|
|
233
|
+
close(): Promise<void>;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export { type Annotations, type DuplexStream, type ExtractParams, type InitCallback, type InitData, type McpServerOptions, type ObservationContext, type ObservationEnd, type ObservedMethod, type Prop, type PropCallback, type RequestObservation, type RequestObserver, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, type ToolCallCallback, type ToolCallDetails, type ToolObservation, type ToolOutcome, createMcpServer, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { ListToolsResult, ServerContext, InputRequiredResult, CallToolResult, Implementation, ClientCapabilities, Server, Transport, JSONRPCMessage } from '@modelcontextprotocol/server';
|
|
2
|
+
import { z } from 'zod/v4';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A web stream that can be both read from and written to.
|
|
6
|
+
*/
|
|
7
|
+
interface DuplexStream<T> {
|
|
8
|
+
readable: ReadableStream<T>;
|
|
9
|
+
writable: WritableStream<T>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Extracts parameter names from a string path.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* type Path = '/schemas/{schema}/tables/{table}';
|
|
16
|
+
* type Params = ExtractParams<Path>; // 'schema' | 'table'
|
|
17
|
+
*/
|
|
18
|
+
type ExtractParams<Path extends string> = Path extends `${string}{${infer P}}${infer Rest}` ? P | ExtractParams<Rest> : never;
|
|
19
|
+
|
|
20
|
+
/** Observations describe handler attempts, not transport delivery or backend commit. */
|
|
21
|
+
type ObservedMethod = 'tools/call' | 'tools/list' | 'resources/list' | 'resources/templates/list' | 'resources/read';
|
|
22
|
+
type ObservationContext<Bucket extends string = never> = Readonly<{
|
|
23
|
+
method: 'tools/call';
|
|
24
|
+
tool: Bucket | 'other';
|
|
25
|
+
}> | Readonly<{
|
|
26
|
+
method: Exclude<ObservedMethod, 'tools/call'>;
|
|
27
|
+
}>;
|
|
28
|
+
type ToolOutcome = 'completed' | 'declined' | 'cancelled';
|
|
29
|
+
type ToolObservation<Fact = never> = Readonly<{
|
|
30
|
+
record: (fact: Fact) => void;
|
|
31
|
+
setOutcome: (result: ToolOutcome) => void;
|
|
32
|
+
}>;
|
|
33
|
+
type ObservationEnd = Readonly<{
|
|
34
|
+
result: ToolOutcome | 'input_required' | 'tool_error' | 'handler_error';
|
|
35
|
+
durationMs: number;
|
|
36
|
+
}>;
|
|
37
|
+
/** Sink failures are isolated; custom facts remain the producer's responsibility. */
|
|
38
|
+
type RequestObservation<Fact = never> = Readonly<{
|
|
39
|
+
record: (fact: Fact) => void | Promise<void>;
|
|
40
|
+
end: (result: ObservationEnd) => void | Promise<void>;
|
|
41
|
+
}>;
|
|
42
|
+
/** Synchronous factory; promises and thenables are unsupported. */
|
|
43
|
+
type RequestObserver<Bucket extends string = never, Fact = never> = (context: ObservationContext<Bucket>) => RequestObservation<Fact> | undefined;
|
|
44
|
+
|
|
45
|
+
type Scheme = string;
|
|
46
|
+
type Annotations = NonNullable<ListToolsResult['tools'][number]['annotations']>;
|
|
47
|
+
type Resource<Uri extends string = string, Result = unknown> = {
|
|
48
|
+
uri: Uri;
|
|
49
|
+
name: string;
|
|
50
|
+
description?: string;
|
|
51
|
+
mimeType?: string;
|
|
52
|
+
read(uri: `${Scheme}://${Uri}`): Promise<Result>;
|
|
53
|
+
};
|
|
54
|
+
type ResourceTemplate<Uri extends string = string, Result = unknown> = {
|
|
55
|
+
uriTemplate: Uri;
|
|
56
|
+
name: string;
|
|
57
|
+
description?: string;
|
|
58
|
+
mimeType?: string;
|
|
59
|
+
read(uri: `${Scheme}://${Uri}`, params: {
|
|
60
|
+
[Param in ExtractParams<Uri>]: string;
|
|
61
|
+
}): Promise<Result>;
|
|
62
|
+
};
|
|
63
|
+
type Tool<Params extends z.ZodObject<any> = z.ZodObject<any>, OutputSchema extends z.ZodObject<any> = z.ZodObject<any>, Fact = never> = {
|
|
64
|
+
description: Prop<string>;
|
|
65
|
+
annotations?: Annotations;
|
|
66
|
+
parameters: Params;
|
|
67
|
+
outputSchema: OutputSchema;
|
|
68
|
+
/** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */
|
|
69
|
+
hidden?: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Executes the tool. `ctx` is the SDK's per-request `ServerContext`
|
|
72
|
+
* (elicitation, multi-round-trip `requestState`, HTTP info, etc.) — most
|
|
73
|
+
* tools ignore it.
|
|
74
|
+
*
|
|
75
|
+
* Returning an `InputRequiredResult` or a direct `CallToolResult` is
|
|
76
|
+
* passed straight to the client instead of being JSON-wrapped; any other
|
|
77
|
+
* value is wrapped as today (`{ content: [{ type: 'text', text:
|
|
78
|
+
* JSON.stringify(value) }] }`).
|
|
79
|
+
*
|
|
80
|
+
* The optional observation handle records custom facts and sets an explicit
|
|
81
|
+
* outcome. Its methods isolate sink failures and become inert after settlement.
|
|
82
|
+
*/
|
|
83
|
+
execute: (params: z.infer<Params>, ctx: ServerContext, observation?: ToolObservation<Fact>) => Promise<z.infer<OutputSchema> | InputRequiredResult | CallToolResult>;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Helper function to define an MCP resource while preserving type information.
|
|
87
|
+
*/
|
|
88
|
+
declare function resource<Uri extends string, Result>(uri: Uri, resource: Omit<Resource<Uri, Result>, 'uri'>): Resource<Uri, Result>;
|
|
89
|
+
/**
|
|
90
|
+
* Helper function to define an MCP resource with a URI template while preserving type information.
|
|
91
|
+
*/
|
|
92
|
+
declare function resourceTemplate<Uri extends string, Result>(uriTemplate: Uri, resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>): ResourceTemplate<Uri, Result>;
|
|
93
|
+
/**
|
|
94
|
+
* Helper function to define a JSON resource while preserving type information.
|
|
95
|
+
*/
|
|
96
|
+
declare function jsonResource<Uri extends string, Result>(uri: Uri, resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>): Resource<Uri, Result>;
|
|
97
|
+
/**
|
|
98
|
+
* Helper function to define a JSON resource with a URI template while preserving type information.
|
|
99
|
+
*/
|
|
100
|
+
declare function jsonResourceTemplate<Uri extends string, Result>(uriTemplate: Uri, resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>): ResourceTemplate<Uri, Result>;
|
|
101
|
+
/**
|
|
102
|
+
* Helper function to define a list of resources that share a common URI scheme.
|
|
103
|
+
*/
|
|
104
|
+
declare function resources<Scheme extends string>(scheme: Scheme, resources: (Resource | ResourceTemplate)[]): (Resource<`${Scheme}://${string}`> | ResourceTemplate<`${Scheme}://${string}`>)[];
|
|
105
|
+
/**
|
|
106
|
+
* Helper function to create a JSON resource response.
|
|
107
|
+
*/
|
|
108
|
+
declare function jsonResourceResponse<Uri extends string, Response>(uri: Uri, response: Response): {
|
|
109
|
+
uri: Uri;
|
|
110
|
+
mimeType: string;
|
|
111
|
+
text: string;
|
|
112
|
+
};
|
|
113
|
+
/**
|
|
114
|
+
* Helper function to define an MCP tool while preserving type information.
|
|
115
|
+
*/
|
|
116
|
+
declare function tool<Params extends z.ZodObject<any>, OutputSchema extends z.ZodObject<any>, Fact = never>(tool: Tool<Params, OutputSchema, Fact>): Tool<Params, OutputSchema, Fact>;
|
|
117
|
+
type InitData = {
|
|
118
|
+
clientInfo: Implementation;
|
|
119
|
+
clientCapabilities: ClientCapabilities;
|
|
120
|
+
};
|
|
121
|
+
type ToolCallBaseDetails = {
|
|
122
|
+
name: string;
|
|
123
|
+
arguments: Record<string, unknown>;
|
|
124
|
+
annotations?: Annotations;
|
|
125
|
+
};
|
|
126
|
+
type ToolCallSuccessDetails = ToolCallBaseDetails & {
|
|
127
|
+
success: true;
|
|
128
|
+
data: unknown;
|
|
129
|
+
};
|
|
130
|
+
type ToolCallErrorDetails = ToolCallBaseDetails & {
|
|
131
|
+
success: false;
|
|
132
|
+
error: unknown;
|
|
133
|
+
};
|
|
134
|
+
type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;
|
|
135
|
+
type InitCallback = (initData: InitData) => void | Promise<void>;
|
|
136
|
+
type ToolCallCallback = (details: ToolCallDetails) => void;
|
|
137
|
+
type PropCallback<T> = () => T | Promise<T>;
|
|
138
|
+
type Prop<T> = T | PropCallback<T>;
|
|
139
|
+
type McpServerOptions<Bucket extends string = never, Fact = never> = {
|
|
140
|
+
/**
|
|
141
|
+
* The name of the MCP server. This will be sent to the client as part of
|
|
142
|
+
* the initialization process.
|
|
143
|
+
*/
|
|
144
|
+
name: string;
|
|
145
|
+
/**
|
|
146
|
+
* The title of the MCP server. This is a human-readable name that can be
|
|
147
|
+
* displayed in the client UI.
|
|
148
|
+
*
|
|
149
|
+
* If not provided, the name will be used as the title.
|
|
150
|
+
*/
|
|
151
|
+
title?: string;
|
|
152
|
+
/**
|
|
153
|
+
* The version of the MCP server. This will be sent to the client as part of
|
|
154
|
+
* the initialization process.
|
|
155
|
+
*/
|
|
156
|
+
version: string;
|
|
157
|
+
/**
|
|
158
|
+
* Callback for when initialization has fully completed with the client.
|
|
159
|
+
*/
|
|
160
|
+
onInitialize?: InitCallback;
|
|
161
|
+
/**
|
|
162
|
+
* Optional instructions describing how to use the server and its features.
|
|
163
|
+
*
|
|
164
|
+
* This can be used by clients to improve the LLM's understanding of available
|
|
165
|
+
* tools, resources, etc. It can be thought of like a "hint" to the model.
|
|
166
|
+
* For example, this information MAY be added to the system prompt.
|
|
167
|
+
*/
|
|
168
|
+
instructions?: string;
|
|
169
|
+
/**
|
|
170
|
+
* Callback for after a tool is called.
|
|
171
|
+
*/
|
|
172
|
+
onToolCall?: ToolCallCallback;
|
|
173
|
+
/**
|
|
174
|
+
* Resources to be served by the server. These can be defined as a static
|
|
175
|
+
* object or as a function that dynamically returns the object synchronously
|
|
176
|
+
* or asynchronously.
|
|
177
|
+
*
|
|
178
|
+
* If defined as a function, the function will be called whenever the client
|
|
179
|
+
* asks for the list of resources or reads a resource. This allows for dynamic
|
|
180
|
+
* resources that can change after the server has started.
|
|
181
|
+
*/
|
|
182
|
+
resources?: Prop<(Resource<string, unknown> | ResourceTemplate<string, unknown>)[]>;
|
|
183
|
+
/**
|
|
184
|
+
* Tools to be served by the server. These can be defined as a static object
|
|
185
|
+
* or as a function that dynamically returns the object synchronously or
|
|
186
|
+
* asynchronously.
|
|
187
|
+
*
|
|
188
|
+
* If defined as a function, the function will be called whenever the client
|
|
189
|
+
* asks for the list of tools or invokes a tool. This allows for dynamic tools
|
|
190
|
+
* that can change after the server has started.
|
|
191
|
+
*/
|
|
192
|
+
tools?: Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>> | ((ctx?: ServerContext) => Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>> | Promise<Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>>);
|
|
193
|
+
/**
|
|
194
|
+
* Multi-round-trip `requestState` integrity hook (protocol revision
|
|
195
|
+
* 2026-07-28), passed straight through to the underlying SDK `Server`.
|
|
196
|
+
*
|
|
197
|
+
* Configure this with `createRequestStateCodec`'s `verify` to
|
|
198
|
+
* authenticate `requestState` a tool mints via `inputRequired(...)`.
|
|
199
|
+
* Leaving it unset keeps the SDK's passthrough behavior.
|
|
200
|
+
*/
|
|
201
|
+
requestState?: {
|
|
202
|
+
verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;
|
|
203
|
+
};
|
|
204
|
+
/** Optional per-request observer; see ObservedMethod for covered handlers. */
|
|
205
|
+
observer?: RequestObserver<Bucket, Fact>;
|
|
206
|
+
classifyTool?: (name: string) => Bucket | 'other';
|
|
207
|
+
};
|
|
208
|
+
/**
|
|
209
|
+
* Creates an MCP server with the given options.
|
|
210
|
+
*
|
|
211
|
+
* Simplifies the process of creating an MCP server by providing a high-level
|
|
212
|
+
* API for defining resources and tools.
|
|
213
|
+
*/
|
|
214
|
+
declare function createMcpServer<Bucket extends string = never, Fact = never>(options: McpServerOptions<Bucket, Fact>): Server;
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* An MCP transport built on top of a duplex stream.
|
|
218
|
+
* It uses a `ReadableStream` to receive messages and a `WritableStream` to send messages.
|
|
219
|
+
*
|
|
220
|
+
* Useful if you wish to pipe messages over your own stream-based transport or directly between two streams.
|
|
221
|
+
*/
|
|
222
|
+
declare class StreamTransport implements Transport, DuplexStream<JSONRPCMessage> {
|
|
223
|
+
#private;
|
|
224
|
+
ready: Promise<void>;
|
|
225
|
+
readable: ReadableStream<JSONRPCMessage>;
|
|
226
|
+
writable: WritableStream<JSONRPCMessage>;
|
|
227
|
+
onclose?: () => void;
|
|
228
|
+
onerror?: (error: Error) => void;
|
|
229
|
+
onmessage?: (message: JSONRPCMessage) => void;
|
|
230
|
+
constructor();
|
|
231
|
+
start(): Promise<void>;
|
|
232
|
+
send(message: JSONRPCMessage): Promise<void>;
|
|
233
|
+
close(): Promise<void>;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export { type Annotations, type DuplexStream, type ExtractParams, type InitCallback, type InitData, type McpServerOptions, type ObservationContext, type ObservationEnd, type ObservedMethod, type Prop, type PropCallback, type RequestObservation, type RequestObserver, type Resource, type ResourceTemplate, type Scheme, StreamTransport, type Tool, type ToolCallCallback, type ToolCallDetails, type ToolObservation, type ToolOutcome, createMcpServer, jsonResource, jsonResourceResponse, jsonResourceTemplate, resource, resourceTemplate, resources, tool };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isCallToolResult as U,Server as k}from"@modelcontextprotocol/server";import{z as E}from"zod/v4";function g(e){try{return new URL(e),e}catch{throw new Error(`invalid uri: ${e}`)}}function O(e,t){let n=new URL(e),r=new URL(t);return n.href===r.href}function w(e,t){let r=new URL(e).pathname.split("/").slice(1);for(let m of t){let l=new URL(m),s=decodeURIComponent(l.pathname).split("/").slice(1);if(r.length!==s.length)continue;let o={},i=!0;for(let c=0;c<r.length;c++){let a=s[c],d=r[c];if(!a||!d)break;if(a.startsWith("{")&&a.endsWith("}")){let p=a.slice(1,-1);if(!p)break;o[p]=d}else if(r[c]!==s[c]){i=!1;break}}if(i)return{uri:m,params:o}}}function x(e,t){if(!e)return;let n=performance.now(),r;try{if(r=e(t),r&&"then"in r&&typeof r.then=="function"){Promise.resolve(r).catch(()=>{});return}}catch{return}if(!r)return;let m=!1,l="completed";return{tool:{record(s){m||S(()=>r.record(s))},setOutcome(s){m||(l=s)}},end(s){if(m)return;m=!0;let o=performance.now()-n;S(()=>r.end({result:s,durationMs:o}))},outcome:()=>l}}function S(e){try{Promise.resolve(e()).catch(()=>{})}catch{}}function I(e,t){return{uri:e,...t}}function B(e,t){return{uriTemplate:e,...t}}function L(e,t){return{uri:e,mimeType:"application/json",...t}}function N(e,t){return{uriTemplate:e,mimeType:"application/json",...t}}function Z(e,t){return t.map(n=>{if("uri"in n){let l=new URL(n.uri,`${e}://`),s=decodeURI(l.href);return{...n,uri:s}}let r=new URL(n.uriTemplate,`${e}://`),m=decodeURI(r.href);return{...n,uriTemplate:m}})}function J(e,t){return{uri:e,mimeType:"application/json",text:JSON.stringify(t)}}function _(e){return e}function A(e){let t={};e.resources&&(t.resources={}),e.tools&&(t.tools={});let n=new k({name:e.name,title:e.title,version:e.version},{capabilities:t,instructions:e.instructions,requestState:e.requestState});async function r(){if(!e.resources)throw new Error("resources not available");return typeof e.resources=="function"?await e.resources():e.resources}async function m(s){if(!e.tools)throw new Error("tools not available");return typeof e.tools=="function"?await e.tools(s):e.tools}async function l(s,o){let i=x(e.observer,{method:s}),c="handler_error";try{let a=await o();return c="isError"in a&&a.isError===!0?"tool_error":"completed",a}finally{i?.end(c)}}return n.oninitialized=async()=>{let s=n.getClientVersion(),o=n.getClientCapabilities();if(!s)throw new Error("client info not available after initialization");if(!o)throw new Error("client capabilities not available after initialization");let i={clientInfo:s,clientCapabilities:o};await e.onInitialize?.(i)},e.resources&&(n.setRequestHandler("resources/list",()=>l("resources/list",async()=>({resources:(await r()).filter(o=>"uri"in o).map(({uri:o,name:i,description:c,mimeType:a})=>({uri:o,name:i,description:c,mimeType:a}))}))),n.setRequestHandler("resources/templates/list",()=>l("resources/templates/list",async()=>({resourceTemplates:(await r()).filter(o=>"uriTemplate"in o).map(({uriTemplate:o,name:i,description:c,mimeType:a})=>({uriTemplate:o,name:i,description:c,mimeType:a}))}))),n.setRequestHandler("resources/read",s=>l("resources/read",async()=>{try{let o=await r(),{uri:i}=s.params,a=o.filter(u=>"uri"in u).find(u=>O(u.uri,i));if(a){let u=await a.read(i);return{contents:Array.isArray(u)?u:[u]}}let d=o.filter(u=>"uriTemplate"in u),p=d.map(({uriTemplate:u})=>g(u)),f=w(i,p);if(!f)throw new Error("resource not found");let y=d.find(u=>u.uriTemplate===f.uri);if(!y)throw new Error("resource not found");let v=await y.read(i,f.params);return{contents:Array.isArray(v)?v:[v]}}catch(o){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:C(o)})}]}}}))),e.tools&&(n.setRequestHandler("tools/list",(s,o)=>l("tools/list",async()=>{let i=await m(o);return{tools:await Promise.all(Object.entries(i).filter(([,c])=>!c.hidden).map(async([c,{description:a,annotations:d,parameters:p}])=>{let f=E.toJSONSchema(p,{target:"draft-7"});return{name:c,description:typeof a=="function"?await a():a,annotations:d,inputSchema:f}}))}})),n.setRequestHandler("tools/call",async(s,o)=>{let i=s.params.name,c="other";if(e.observer)try{c=e.classifyTool?.(i)??"other"}catch{}let a=x(e.observer,{method:"tools/call",tool:c}),d="handler_error";try{let p=await m(o);if(!(i in p))throw new Error("tool not found");let f=p[i];if(!f)throw new Error("tool not found");let y=f.parameters.strict().parse(s.params.arguments??{}),R=await(async h=>{let T=await h.execute(y,o,a?.tool).then(b=>({success:!0,data:b})).catch(b=>({success:!1,error:b}));try{e.onToolCall?.({name:i,arguments:y,annotations:h.annotations,...T})}catch(b){console.error("Failed to run tool callback",b)}if(!T.success)throw T.error;return T.data})(f);if(j(R))return d="input_required",R;if(U(R))return d=R.isError?"tool_error":a?.outcome()??"completed",R;let u=R!=null?[{type:"text",text:JSON.stringify(R)}]:[];return d=a?.outcome()??"completed",{content:u}}catch(p){let f={isError:!0,content:[{type:"text",text:JSON.stringify({error:C(p)})}]};return d="tool_error",f}finally{a?.end(d)}})),n}function j(e){return typeof e=="object"&&e!==null&&e.resultType==="input_required"}function C(e){if(!e||typeof e!="object")return e;let t={},n=["name","message"];for(let r of n)r in e&&(t[r]=e[r]);return t}var P=class{#e;#t;ready;readable;writable;onclose;onerror;onmessage;constructor(){let t,n,r=new Promise(l=>{t=l}),m=new Promise(l=>{n=l});this.ready=Promise.all([r,m]).then(()=>{}),this.readable=new ReadableStream({start:l=>{this.#e=l,t()}}),this.writable=new WritableStream({start:l=>{this.#t=l,n()},write:l=>{this.onmessage?.(l)}})}async start(){await this.ready}async send(t){if(!this.#e)throw new Error("readable stream not initialized");this.#e.enqueue(t)}async close(){this.#e?.error(new Error("connection closed")),this.#t?.error(new Error("connection closed")),this.onclose?.()}};export{P as StreamTransport,A as createMcpServer,L as jsonResource,J as jsonResourceResponse,N as jsonResourceTemplate,I as resource,B as resourceTemplate,Z as resources,_ as tool};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/util.ts","../src/observation.ts","../src/stream-transport.ts"],"sourcesContent":["import { isCallToolResult, Server } from '@modelcontextprotocol/server';\nimport type {\n CallToolResult,\n ClientCapabilities,\n Implementation,\n InputRequiredResult,\n ListResourcesResult,\n ListResourceTemplatesResult,\n ListToolsResult,\n Tool as McpTool,\n ReadResourceResult,\n ServerCapabilities,\n ServerContext,\n} from '@modelcontextprotocol/server';\nimport { z } from 'zod/v4';\n\nimport type { ExtractParams } from './types.js';\nimport { assertValidUri, compareUris, matchUriTemplate } from './util.js';\nimport { beginObservation } from './observation.js';\nimport type {\n ObservationEnd,\n ObservedMethod,\n ToolObservation,\n RequestObserver,\n} from './observation.js';\n\nexport type Scheme = string;\nexport type Annotations = NonNullable<\n ListToolsResult['tools'][number]['annotations']\n>;\n\nexport type Resource<Uri extends string = string, Result = unknown> = {\n uri: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(uri: `${Scheme}://${Uri}`): Promise<Result>;\n};\n\nexport type ResourceTemplate<Uri extends string = string, Result = unknown> = {\n uriTemplate: Uri;\n name: string;\n description?: string;\n mimeType?: string;\n read(\n uri: `${Scheme}://${Uri}`,\n params: {\n [Param in ExtractParams<Uri>]: string;\n }\n ): Promise<Result>;\n};\n\nexport type Tool<\n Params extends z.ZodObject<any> = z.ZodObject<any>,\n // MCP spec restricts outputSchema to type \"object\" at the root level:\n // https://modelcontextprotocol.io/specification/2025-11-25/schema#tool-outputschema\n OutputSchema extends z.ZodObject<any> = z.ZodObject<any>,\n Fact = never,\n> = {\n description: Prop<string>;\n annotations?: Annotations;\n parameters: Params;\n outputSchema: OutputSchema;\n /** If true, excludes the tool from `tools/list` while keeping it callable via `tools/call`. */\n hidden?: boolean;\n /**\n * Executes the tool. `ctx` is the SDK's per-request `ServerContext`\n * (elicitation, multi-round-trip `requestState`, HTTP info, etc.) — most\n * tools ignore it.\n *\n * Returning an `InputRequiredResult` or a direct `CallToolResult` is\n * passed straight to the client instead of being JSON-wrapped; any other\n * value is wrapped as today (`{ content: [{ type: 'text', text:\n * JSON.stringify(value) }] }`).\n *\n * The optional observation handle records custom facts and sets an explicit\n * outcome. Its methods isolate sink failures and become inert after settlement.\n */\n execute: (\n params: z.infer<Params>,\n ctx: ServerContext,\n observation?: ToolObservation<Fact>\n ) => Promise<z.infer<OutputSchema> | InputRequiredResult | CallToolResult>;\n};\n\n/**\n * Helper function to define an MCP resource while preserving type information.\n */\nexport function resource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri'>\n): Resource<Uri, Result> {\n return {\n uri,\n ...resource,\n };\n}\n\n/**\n * Helper function to define an MCP resource with a URI template while preserving type information.\n */\nexport function resourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource while preserving type information.\n */\nexport function jsonResource<Uri extends string, Result>(\n uri: Uri,\n resource: Omit<Resource<Uri, Result>, 'uri' | 'mimeType'>\n): Resource<Uri, Result> {\n return {\n uri,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a JSON resource with a URI template while preserving type information.\n */\nexport function jsonResourceTemplate<Uri extends string, Result>(\n uriTemplate: Uri,\n resource: Omit<ResourceTemplate<Uri, Result>, 'uriTemplate' | 'mimeType'>\n): ResourceTemplate<Uri, Result> {\n return {\n uriTemplate,\n mimeType: 'application/json' as const,\n ...resource,\n };\n}\n\n/**\n * Helper function to define a list of resources that share a common URI scheme.\n */\nexport function resources<Scheme extends string>(\n scheme: Scheme,\n resources: (Resource | ResourceTemplate)[]\n): (\n | Resource<`${Scheme}://${string}`>\n | ResourceTemplate<`${Scheme}://${string}`>\n)[] {\n return resources.map((resource) => {\n if ('uri' in resource) {\n const url = new URL(resource.uri, `${scheme}://`);\n const uri = decodeURI(url.href) as `${Scheme}://${typeof resource.uri}`;\n\n return {\n ...resource,\n uri,\n };\n }\n\n const url = new URL(resource.uriTemplate, `${scheme}://`);\n const uriTemplate = decodeURI(\n url.href\n ) as `${Scheme}://${typeof resource.uriTemplate}`;\n\n return {\n ...resource,\n uriTemplate,\n };\n });\n}\n\n/**\n * Helper function to create a JSON resource response.\n */\nexport function jsonResourceResponse<Uri extends string, Response>(\n uri: Uri,\n response: Response\n) {\n return {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(response),\n };\n}\n\n/**\n * Helper function to define an MCP tool while preserving type information.\n */\nexport function tool<\n Params extends z.ZodObject<any>,\n OutputSchema extends z.ZodObject<any>,\n Fact = never,\n>(tool: Tool<Params, OutputSchema, Fact>) {\n return tool;\n}\n\nexport type InitData = {\n clientInfo: Implementation;\n clientCapabilities: ClientCapabilities;\n};\n\ntype ToolCallBaseDetails = {\n name: string;\n arguments: Record<string, unknown>;\n annotations?: Annotations;\n};\n\ntype ToolCallSuccessDetails = ToolCallBaseDetails & {\n success: true;\n data: unknown;\n};\n\ntype ToolCallErrorDetails = ToolCallBaseDetails & {\n success: false;\n error: unknown;\n};\n\nexport type ToolCallDetails = ToolCallSuccessDetails | ToolCallErrorDetails;\n\nexport type InitCallback = (initData: InitData) => void | Promise<void>;\nexport type ToolCallCallback = (details: ToolCallDetails) => void;\nexport type PropCallback<T> = () => T | Promise<T>;\nexport type Prop<T> = T | PropCallback<T>;\n\nexport type McpServerOptions<Bucket extends string = never, Fact = never> = {\n /**\n * The name of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n name: string;\n\n /**\n * The title of the MCP server. This is a human-readable name that can be\n * displayed in the client UI.\n *\n * If not provided, the name will be used as the title.\n */\n title?: string;\n\n /**\n * The version of the MCP server. This will be sent to the client as part of\n * the initialization process.\n */\n version: string;\n\n /**\n * Callback for when initialization has fully completed with the client.\n */\n onInitialize?: InitCallback;\n\n /**\n * Optional instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available\n * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n * For example, this information MAY be added to the system prompt.\n */\n instructions?: string;\n\n /**\n * Callback for after a tool is called.\n */\n onToolCall?: ToolCallCallback;\n\n /**\n * Resources to be served by the server. These can be defined as a static\n * object or as a function that dynamically returns the object synchronously\n * or asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of resources or reads a resource. This allows for dynamic\n * resources that can change after the server has started.\n */\n resources?: Prop<\n (Resource<string, unknown> | ResourceTemplate<string, unknown>)[]\n >;\n\n /**\n * Tools to be served by the server. These can be defined as a static object\n * or as a function that dynamically returns the object synchronously or\n * asynchronously.\n *\n * If defined as a function, the function will be called whenever the client\n * asks for the list of tools or invokes a tool. This allows for dynamic tools\n * that can change after the server has started.\n */\n tools?:\n | Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n | ((\n ctx?: ServerContext\n ) =>\n | Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n | Promise<\n Record<string, Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>>\n >);\n\n /**\n * Multi-round-trip `requestState` integrity hook (protocol revision\n * 2026-07-28), passed straight through to the underlying SDK `Server`.\n *\n * Configure this with `createRequestStateCodec`'s `verify` to\n * authenticate `requestState` a tool mints via `inputRequired(...)`.\n * Leaving it unset keeps the SDK's passthrough behavior.\n */\n requestState?: {\n verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;\n };\n\n /** Optional per-request observer; see ObservedMethod for covered handlers. */\n observer?: RequestObserver<Bucket, Fact>;\n classifyTool?: (name: string) => Bucket | 'other';\n};\n\n/**\n * Creates an MCP server with the given options.\n *\n * Simplifies the process of creating an MCP server by providing a high-level\n * API for defining resources and tools.\n */\nexport function createMcpServer<Bucket extends string = never, Fact = never>(\n options: McpServerOptions<Bucket, Fact>\n) {\n const capabilities: ServerCapabilities = {};\n\n if (options.resources) {\n capabilities.resources = {};\n }\n\n if (options.tools) {\n capabilities.tools = {};\n }\n\n const server = new Server(\n {\n name: options.name,\n title: options.title,\n version: options.version,\n },\n {\n capabilities,\n instructions: options.instructions,\n requestState: options.requestState,\n }\n );\n\n async function getResources() {\n if (!options.resources) {\n throw new Error('resources not available');\n }\n\n return typeof options.resources === 'function'\n ? await options.resources()\n : options.resources;\n }\n\n async function getTools(ctx?: ServerContext) {\n if (!options.tools) {\n throw new Error('tools not available');\n }\n\n return typeof options.tools === 'function'\n ? await options.tools(ctx)\n : options.tools;\n }\n\n async function observed<Result extends object>(\n method: Exclude<ObservedMethod, 'tools/call'>,\n run: () => Promise<Result>\n ): Promise<Result> {\n const scope = beginObservation(options.observer, { method });\n let outcome: ObservationEnd['result'] = 'handler_error';\n try {\n const result = await run();\n outcome =\n 'isError' in result && result.isError === true\n ? 'tool_error'\n : 'completed';\n return result;\n } finally {\n scope?.end(outcome);\n }\n }\n\n server.oninitialized = async () => {\n const clientInfo = server.getClientVersion();\n const clientCapabilities = server.getClientCapabilities();\n\n if (!clientInfo) {\n throw new Error('client info not available after initialization');\n }\n\n if (!clientCapabilities) {\n throw new Error('client capabilities not available after initialization');\n }\n\n const initData: InitData = {\n clientInfo,\n clientCapabilities,\n };\n\n await options.onInitialize?.(initData);\n };\n\n if (options.resources) {\n server.setRequestHandler(\n 'resources/list',\n (): Promise<ListResourcesResult> =>\n observed('resources/list', async () => {\n const allResources = await getResources();\n return {\n resources: allResources\n .filter((resource) => 'uri' in resource)\n .map(({ uri, name, description, mimeType }) => {\n return {\n uri,\n name,\n description,\n mimeType,\n };\n }),\n };\n })\n );\n\n server.setRequestHandler(\n 'resources/templates/list',\n (): Promise<ListResourceTemplatesResult> =>\n observed('resources/templates/list', async () => {\n const allResources = await getResources();\n return {\n resourceTemplates: allResources\n .filter((resource) => 'uriTemplate' in resource)\n .map(({ uriTemplate, name, description, mimeType }) => {\n return {\n uriTemplate,\n name,\n description,\n mimeType,\n };\n }),\n };\n })\n );\n\n server.setRequestHandler(\n 'resources/read',\n (request): Promise<ReadResourceResult> =>\n observed('resources/read', async () => {\n try {\n const allResources = await getResources();\n const { uri } = request.params;\n\n const resources = allResources.filter(\n (resource) => 'uri' in resource\n );\n const resource = resources.find((resource) =>\n compareUris(resource.uri, uri)\n );\n\n if (resource) {\n const result = await resource.read(\n uri as `${string}://${string}`\n );\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n }\n\n const resourceTemplates = allResources.filter(\n (resource) => 'uriTemplate' in resource\n );\n const resourceTemplateUris = resourceTemplates.map(\n ({ uriTemplate }) => assertValidUri(uriTemplate)\n );\n\n const templateMatch = matchUriTemplate(uri, resourceTemplateUris);\n\n if (!templateMatch) {\n throw new Error('resource not found');\n }\n\n const resourceTemplate = resourceTemplates.find(\n (r) => r.uriTemplate === templateMatch.uri\n );\n\n if (!resourceTemplate) {\n throw new Error('resource not found');\n }\n\n const result = await resourceTemplate.read(\n uri as `${string}://${string}`,\n templateMatch.params\n );\n\n const contents = Array.isArray(result) ? result : [result];\n\n return {\n contents,\n };\n } catch (error) {\n // Preserve the existing resource error payload despite the SDK result type.\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } as unknown as ReadResourceResult;\n }\n })\n );\n }\n\n if (options.tools) {\n server.setRequestHandler(\n 'tools/list',\n (_request, ctx): Promise<ListToolsResult> =>\n observed('tools/list', async () => {\n const tools = await getTools(ctx);\n\n return {\n tools: await Promise.all(\n Object.entries(tools)\n .filter(([, tool]) => !tool.hidden)\n .map(\n async ([name, { description, annotations, parameters }]) => {\n const inputSchema = z.toJSONSchema(parameters, {\n target: 'draft-7',\n });\n\n return {\n name,\n description:\n typeof description === 'function'\n ? await description()\n : description,\n annotations,\n // Casting the same as the SDK does:\n // https://github.com/modelcontextprotocol/typescript-sdk/blob/fb07af810b51003c338dc4885a9e42f54519f9af/src/server/mcp.ts#L154\n inputSchema: inputSchema as McpTool['inputSchema'],\n };\n }\n )\n ),\n } satisfies ListToolsResult;\n })\n );\n\n server.setRequestHandler('tools/call', async (request, ctx) => {\n const toolName = request.params.name;\n let tool: Bucket | 'other' = 'other';\n if (options.observer) {\n try {\n tool = options.classifyTool?.(toolName) ?? 'other';\n } catch {}\n }\n const scope = beginObservation(options.observer, {\n method: 'tools/call',\n tool,\n });\n let outcome: ObservationEnd['result'] = 'handler_error';\n\n try {\n const tools = await getTools(ctx);\n\n if (!(toolName in tools)) {\n throw new Error('tool not found');\n }\n\n const tool = tools[toolName];\n\n if (!tool) {\n throw new Error('tool not found');\n }\n const args = tool.parameters\n .strict()\n .parse(request.params.arguments ?? {});\n\n const executeWithCallback = async (\n tool: Tool<z.ZodObject<any>, z.ZodObject<any>, Fact>\n ) => {\n // Wrap success or error in a result value\n const res = await tool\n .execute(args, ctx, scope?.tool)\n .then((data: unknown) => ({ success: true as const, data }))\n .catch((error) => ({ success: false as const, error }));\n\n try {\n options.onToolCall?.({\n name: toolName,\n arguments: args,\n annotations: tool.annotations,\n ...res,\n });\n } catch (error) {\n // Don't fail the tool call if the callback fails\n console.error('Failed to run tool callback', error);\n }\n\n // Unwrap result\n if (!res.success) {\n throw res.error;\n }\n return res.data;\n };\n\n const result = await executeWithCallback(tool);\n\n // An InputRequiredResult is already shaped for the wire.\n if (isInputRequiredResult(result)) {\n outcome = 'input_required';\n return result;\n }\n\n // A direct CallToolResult is already shaped for the wire; pass it\n // through instead of JSON-wrapping it.\n if (isCallToolResult(result)) {\n outcome = result.isError\n ? 'tool_error'\n : (scope?.outcome() ?? 'completed');\n return result;\n }\n\n const content =\n result != null\n ? [{ type: 'text' as const, text: JSON.stringify(result) }]\n : [];\n\n outcome = scope?.outcome() ?? 'completed';\n return {\n content,\n };\n } catch (error) {\n const result = {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({ error: enumerateError(error) }),\n },\n ],\n } satisfies CallToolResult;\n outcome = 'tool_error';\n return result;\n } finally {\n scope?.end(outcome);\n }\n });\n }\n\n return server;\n}\n\nfunction isInputRequiredResult(value: unknown): value is InputRequiredResult {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { resultType?: unknown }).resultType === 'input_required'\n );\n}\n\nfunction enumerateError(error: unknown) {\n if (!error) {\n return error;\n }\n\n if (typeof error !== 'object') {\n return error;\n }\n\n const newError: Record<string, unknown> = {};\n\n const errorProps = ['name', 'message'] as const;\n\n for (const prop of errorProps) {\n if (prop in error) {\n newError[prop] = (error as Record<string, unknown>)[prop];\n }\n }\n\n return newError;\n}\n","import type { ExtractParams } from './types.js';\n\n/**\n * Asserts that a URI is valid.\n */\nexport function assertValidUri(uri: string) {\n try {\n new URL(uri);\n return uri;\n } catch {\n throw new Error(`invalid uri: ${uri}`);\n }\n}\n\n/**\n * Compares two URIs.\n */\nexport function compareUris(uriA: string, uriB: string): boolean {\n const urlA = new URL(uriA);\n const urlB = new URL(uriB);\n\n return urlA.href === urlB.href;\n}\n\n/**\n * Matches a URI to a RFC 6570 URI Template (resourceUris) and extracts\n * the parameters.\n *\n * Currently only supports simple string parameters.\n */\nexport function matchUriTemplate<Templates extends string[]>(\n uri: string,\n uriTemplates: Templates\n):\n | {\n uri: Templates[number];\n params: { [Param in ExtractParams<Templates[number]>]: string };\n }\n | undefined {\n const url = new URL(uri);\n const segments = url.pathname.split('/').slice(1);\n\n for (const resourceUri of uriTemplates) {\n const resourceUrl = new URL(resourceUri);\n const resourceSegments = decodeURIComponent(resourceUrl.pathname)\n .split('/')\n .slice(1);\n\n if (segments.length !== resourceSegments.length) {\n continue;\n }\n\n const params: Record<string, string> = {};\n let isMatch = true;\n\n for (let i = 0; i < segments.length; i++) {\n const resourceSegment = resourceSegments[i];\n const segment = segments[i];\n\n if (!resourceSegment || !segment) {\n break;\n }\n\n if (resourceSegment.startsWith('{') && resourceSegment.endsWith('}')) {\n const paramKey = resourceSegment.slice(1, -1);\n\n if (!paramKey) {\n break;\n }\n\n params[paramKey] = segment;\n } else if (segments[i] !== resourceSegments[i]) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n return {\n uri: resourceUri,\n params: params as {\n [Param in ExtractParams<Templates[number]>]: string;\n },\n };\n }\n }\n}\n","/** Observations describe handler attempts, not transport delivery or backend commit. */\nexport type ObservedMethod =\n | 'tools/call'\n | 'tools/list'\n | 'resources/list'\n | 'resources/templates/list'\n | 'resources/read';\n\nexport type ObservationContext<Bucket extends string = never> =\n | Readonly<{ method: 'tools/call'; tool: Bucket | 'other' }>\n | Readonly<{ method: Exclude<ObservedMethod, 'tools/call'> }>;\n\nexport type ToolOutcome = 'completed' | 'declined' | 'cancelled';\n\nexport type ToolObservation<Fact = never> = Readonly<{\n record: (fact: Fact) => void;\n setOutcome: (result: ToolOutcome) => void;\n}>;\n\nexport type ObservationEnd = Readonly<{\n result: ToolOutcome | 'input_required' | 'tool_error' | 'handler_error';\n durationMs: number;\n}>;\n\n/** Sink failures are isolated; custom facts remain the producer's responsibility. */\nexport type RequestObservation<Fact = never> = Readonly<{\n record: (fact: Fact) => void | Promise<void>;\n end: (result: ObservationEnd) => void | Promise<void>;\n}>;\n\n/** Synchronous factory; promises and thenables are unsupported. */\nexport type RequestObserver<Bucket extends string = never, Fact = never> = (\n context: ObservationContext<Bucket>\n) => RequestObservation<Fact> | undefined;\n\n/** Package-internal lifecycle controls are never passed to a tool. */\nexport type ObservationScope<Fact = never> = Readonly<{\n tool: ToolObservation<Fact>;\n end: (result: ObservationEnd['result']) => void;\n outcome: () => ToolOutcome;\n}>;\n\n/**\n * Factory and sink failures are contained, never awaited or logged.\n * Synchronous callbacks can still block; this is not a CPU sandbox.\n */\nexport function beginObservation<Bucket extends string = never, Fact = never>(\n observer: RequestObserver<Bucket, Fact> | undefined,\n context: ObservationContext<Bucket>\n): ObservationScope<Fact> | undefined {\n if (!observer) return undefined;\n const start = performance.now();\n let observation: RequestObservation<Fact> | undefined;\n try {\n observation = observer(context);\n if (\n observation &&\n 'then' in observation &&\n typeof observation.then === 'function'\n ) {\n void Promise.resolve(observation).catch(() => {});\n return undefined;\n }\n } catch {\n return undefined;\n }\n if (!observation) return undefined;\n\n let ended = false;\n let outcome: ToolOutcome = 'completed';\n return {\n tool: {\n record(fact): void {\n if (!ended) safeCall(() => observation.record(fact));\n },\n setOutcome(result): void {\n if (!ended) outcome = result;\n },\n },\n end(result): void {\n if (ended) return;\n ended = true;\n const durationMs = performance.now() - start;\n safeCall(() => observation.end({ result, durationMs }));\n },\n outcome: () => outcome,\n };\n}\n\nfunction safeCall(action: () => void | Promise<void>): void {\n try {\n void Promise.resolve(action()).catch(() => {});\n } catch {\n // Telemetry-only failure: never surface, retry, or log the raw value.\n }\n}\n","import type { JSONRPCMessage, Transport } from '@modelcontextprotocol/server';\n\nimport type { DuplexStream } from './types.js';\n\n/**\n * An MCP transport built on top of a duplex stream.\n * It uses a `ReadableStream` to receive messages and a `WritableStream` to send messages.\n *\n * Useful if you wish to pipe messages over your own stream-based transport or directly between two streams.\n */\nexport class StreamTransport\n implements Transport, DuplexStream<JSONRPCMessage>\n{\n #readableStreamController?: ReadableStreamDefaultController<JSONRPCMessage>;\n #writeableStreamController?: WritableStreamDefaultController;\n\n ready: Promise<void>;\n\n readable: ReadableStream<JSONRPCMessage>;\n writable: WritableStream<JSONRPCMessage>;\n\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n\n constructor() {\n let resolveReadReady: () => void;\n let resolveWriteReady: () => void;\n\n const readReady = new Promise<void>((resolve) => {\n resolveReadReady = resolve;\n });\n\n const writeReady = new Promise<void>((resolve) => {\n resolveWriteReady = resolve;\n });\n\n this.ready = Promise.all([readReady, writeReady]).then(() => {});\n\n this.readable = new ReadableStream({\n start: (controller) => {\n this.#readableStreamController = controller;\n resolveReadReady();\n },\n });\n\n this.writable = new WritableStream({\n start: (controller) => {\n this.#writeableStreamController = controller;\n resolveWriteReady();\n },\n write: (message) => {\n this.onmessage?.(message);\n },\n });\n }\n\n async start() {\n await this.ready;\n }\n\n async send(message: JSONRPCMessage) {\n if (!this.#readableStreamController) {\n throw new Error('readable stream not initialized');\n }\n this.#readableStreamController.enqueue(message);\n }\n\n async close() {\n this.#readableStreamController?.error(new Error('connection closed'));\n this.#writeableStreamController?.error(new Error('connection closed'));\n this.onclose?.();\n }\n}\n"],"mappings":"AAAA,OAAS,oBAAAA,EAAkB,UAAAC,MAAc,+BAczC,OAAS,KAAAC,MAAS,SCTX,SAASC,EAAeC,EAAa,CAC1C,GAAI,CACF,WAAI,IAAIA,CAAG,EACJA,CACT,MAAQ,CACN,MAAM,IAAI,MAAM,gBAAgBA,CAAG,EAAE,CACvC,CACF,CAKO,SAASC,EAAYC,EAAcC,EAAuB,CAC/D,IAAMC,EAAO,IAAI,IAAIF,CAAI,EACnBG,EAAO,IAAI,IAAIF,CAAI,EAEzB,OAAOC,EAAK,OAASC,EAAK,IAC5B,CAQO,SAASC,EACdN,EACAO,EAMY,CAEZ,IAAMC,EADM,IAAI,IA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","Server","z","assertValidUri","uri","compareUris","uriA","uriB","urlA","urlB","matchUriTemplate","uriTemplates","segments","resourceUri","resourceUrl","resourceSegments","params","isMatch","i","resourceSegment","segment","paramKey","beginObservation","observer","context","start","observation","ended","outcome","fact","safeCall","result","durationMs","action","resource","uri","resourceTemplate","uriTemplate","jsonResource","jsonResourceTemplate","resources","scheme","url","jsonResourceResponse","response","tool","createMcpServer","options","capabilities","server","Server","getResources","getTools","ctx","observed","method","run","scope","beginObservation","outcome","result","clientInfo","clientCapabilities","initData","name","description","mimeType","request","allResources","compareUris","resourceTemplates","resourceTemplateUris","assertValidUri","templateMatch","matchUriTemplate","r","error","enumerateError","_request","tools","annotations","parameters","inputSchema","z","toolName","args","res","data","isInputRequiredResult","isCallToolResult","content","value","newError","errorProps","prop","StreamTransport","#readableStreamController","#writeableStreamController","resolveReadReady","resolveWriteReady","readReady","resolve","writeReady","controller","message"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@schemarch/mcp-utils",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.9.0",
|
|
4
|
+
"description": "MCP utilities",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/schemarch/mcp.git"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"main": "dist/index.cjs",
|
|
12
|
+
"types": "dist/index.d.ts",
|
|
13
|
+
"sideEffects": false,
|
|
14
|
+
"files": [
|
|
15
|
+
"dist/**/*"
|
|
16
|
+
],
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"import": "./dist/index.js",
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"default": "./dist/index.cjs"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"@modelcontextprotocol/server": "^2.0.0",
|
|
26
|
+
"zod": "^3.25.0 || ^4.0.0"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@modelcontextprotocol/client": "^2.0.0",
|
|
30
|
+
"@modelcontextprotocol/server": "^2.0.0",
|
|
31
|
+
"@total-typescript/tsconfig": "^1.0.4",
|
|
32
|
+
"@types/node": "^22.8.6",
|
|
33
|
+
"prettier": "^3.3.3",
|
|
34
|
+
"tsup": "^8.3.5",
|
|
35
|
+
"typescript": "^5.6.3",
|
|
36
|
+
"vitest": "^2.1.9",
|
|
37
|
+
"zod": "^3.25.0 || ^4.0.0"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsup --clean",
|
|
41
|
+
"dev": "tsup --watch",
|
|
42
|
+
"typecheck": "tsc --noEmit",
|
|
43
|
+
"prebuild": "pnpm typecheck",
|
|
44
|
+
"test": "vitest",
|
|
45
|
+
"test:coverage": "vitest --coverage"
|
|
46
|
+
}
|
|
6
47
|
}
|