@jangmanj/mcp-client 0.8.0 → 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/README.md CHANGED
@@ -75,13 +75,59 @@ const connection = await connect({
75
75
  For interactive OAuth (discovery, PKCE, CIMD/DCR), construct `OAuthAuthorization` from
76
76
  `/auth` with your consent/browser/redirect ports and pass it as `authProvider`.
77
77
 
78
+ ## Building a server
79
+
80
+ `@jangmanj/mcp-client/server` covers the ordinary MCP 2026-07-28 request
81
+ surface; `@jangmanj/mcp-client/server-events` covers push. Both are
82
+ transport-agnostic — your host owns JSON-RPC dispatch, error mapping, and
83
+ listeners.
84
+
85
+ ```ts
86
+ import { McpServer } from "@jangmanj/mcp-client/server";
87
+ import { EventBus, EventsServer, SubscriptionsServer, TaskCenter } from "@jangmanj/mcp-client/server-events";
88
+
89
+ const bus = new EventBus();
90
+ const subscriptions = new SubscriptionsServer({ capabilities: { tools: { listChanged: true } } });
91
+ const server = new McpServer({
92
+ serverInfo: { name: "roger-wilco", version: "0.1.0" },
93
+ subscriptions,
94
+ events: new EventsServer({ bus }),
95
+ tasks: new TaskCenter({ bus }),
96
+ });
97
+
98
+ server.registerTool({
99
+ name: "roger_send",
100
+ inputSchema: { type: "object", properties: { body: { type: "string" } }, required: ["body"] },
101
+ handler: async ({ body }) => {
102
+ const mail = bus.publish("roger.mail", { body });
103
+ return { content: [{ type: "text", text: mail.eventId }] };
104
+ },
105
+ });
106
+ server.registerResource({ uri: "file:///board", name: "board", handler: () => "..." });
107
+ server.registerPrompt({ name: "reply", handler: () => ({ messages: [] }) });
108
+
109
+ // Ordinary JSON-RPC requests (tools/list, tools/call, resources/read,
110
+ // prompts/get, completion/complete, server/discover, events/*, tasks/*):
111
+ const result = await server.handleRequest(msg); // throws ServerError(code) for the host to map
112
+
113
+ // Long-lived streams still use host channels:
114
+ // subscriptions.listen(channel, params) / server.events?.stream(channel, params)
115
+ ```
116
+
117
+ Included: deterministic pagination with opaque cursors, required `resultType`
118
+ and cache hints, input/output schema validation (Ajv 2020-12), resource
119
+ templates, prompt arguments, completion capping, MRTR `input_required` and
120
+ HMAC-protected `requestState` helpers, and task-handle results. Deprecated
121
+ Logging/Roots/Sampling are intentionally absent.
122
+
78
123
  ## Push on the server side
79
124
 
80
125
  `@jangmanj/mcp-client/server-events` is the modular, transport-agnostic server
81
126
  companion: event logs with cursors, live `events/stream`, standard
82
- `subscriptions/listen`, notices, and optional async tasks. It is deliberately
83
- not a tools/resources/prompts server framework — mount it in your own host and
84
- let the host own JSON-RPC dispatch and transports.
127
+ `subscriptions/listen`, notices, and optional async tasks. It contains no
128
+ tools/resources/prompts registry of its own — that lives in
129
+ `@jangmanj/mcp-client/server` — so you can adopt push without adopting a
130
+ framework.
85
131
 
86
132
  ```ts
87
133
  import { EventBus, EventsServer, SubscriptionsServer, TaskCenter, Notices } from "@jangmanj/mcp-client/server-events";
@@ -194,6 +240,7 @@ const ops = createOps(client);
194
240
  - `@jangmanj/mcp-client/client` (high-level `connect()` API)
195
241
  - `@jangmanj/mcp-client/testing` (in-memory transport / fake tool server)
196
242
  - `@jangmanj/mcp-client/server-events` (push-first server building blocks)
243
+ - `@jangmanj/mcp-client/server` (tools/resources/prompts/discover/completion server)
197
244
  - `@jangmanj/mcp-client/auth`
198
245
  - `@jangmanj/mcp-client/ops`
199
246
  - `@jangmanj/mcp-client/mrtr-cache`
@@ -0,0 +1,4 @@
1
+ export * from "./protocol.js";
2
+ export * from "./mrtr.js";
3
+ export * from "./uri.js";
4
+ export * from "./server.js";
@@ -0,0 +1,4 @@
1
+ export * from "./protocol.js";
2
+ export * from "./mrtr.js";
3
+ export * from "./uri.js";
4
+ export * from "./server.js";
@@ -0,0 +1,15 @@
1
+ import { type Obj } from "../server-events/index.js";
2
+ /** Multi Round-Trip Request interim result. At least one field is required. */
3
+ export declare function inputRequired(input: {
4
+ readonly inputRequests?: Record<string, {
5
+ readonly method: string;
6
+ readonly params: Obj;
7
+ }>;
8
+ readonly requestState?: string;
9
+ }): Obj;
10
+ /** Opaque, integrity-protected requestState (HMAC-SHA256 over method + payload). */
11
+ export declare function issueRequestState(secret: string, method: string, payload?: Obj): string;
12
+ /** Verify and decode requestState; tampered or wrong-method state is rejected. */
13
+ export declare function verifyRequestState(secret: string, state: unknown, method: string): Obj;
14
+ /** Validate a retry's inputResponses shape; unknown keys are ignored by design. */
15
+ export declare function readInputResponses(params: Obj): Obj | undefined;
@@ -0,0 +1,55 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { ServerError } from "../server-events/index.js";
3
+ /** Multi Round-Trip Request interim result. At least one field is required. */
4
+ export function inputRequired(input) {
5
+ if (input.inputRequests === undefined && input.requestState === undefined) {
6
+ throw new ServerError(-32603, "input_required needs inputRequests or requestState");
7
+ }
8
+ return {
9
+ resultType: "input_required",
10
+ ...(input.inputRequests !== undefined ? { inputRequests: input.inputRequests } : {}),
11
+ ...(input.requestState !== undefined ? { requestState: input.requestState } : {}),
12
+ };
13
+ }
14
+ /** Opaque, integrity-protected requestState (HMAC-SHA256 over method + payload). */
15
+ export function issueRequestState(secret, method, payload = {}) {
16
+ const body = Buffer.from(JSON.stringify({ method, payload }), "utf8");
17
+ const signature = createHmac("sha256", secret).update(body).digest("base64url");
18
+ return `${body.toString("base64url")}.${signature}`;
19
+ }
20
+ /** Verify and decode requestState; tampered or wrong-method state is rejected. */
21
+ export function verifyRequestState(secret, state, method) {
22
+ if (typeof state !== "string")
23
+ throw new ServerError(-32602, "requestState must be a string");
24
+ const [encoded, signature] = state.split(".");
25
+ if (!encoded || !signature)
26
+ throw new ServerError(-32602, "invalid requestState");
27
+ const body = Buffer.from(encoded, "base64url");
28
+ const expected = createHmac("sha256", secret).update(body).digest("base64url");
29
+ const a = Buffer.from(signature);
30
+ const b = Buffer.from(expected);
31
+ if (a.length !== b.length || !timingSafeEqual(a, b))
32
+ throw new ServerError(-32602, "invalid requestState");
33
+ try {
34
+ const parsed = JSON.parse(body.toString("utf8"));
35
+ if (parsed.method !== method || typeof parsed.payload !== "object" || parsed.payload === null) {
36
+ throw new ServerError(-32602, "requestState method mismatch");
37
+ }
38
+ return parsed.payload;
39
+ }
40
+ catch (error) {
41
+ if (error instanceof ServerError)
42
+ throw error;
43
+ throw new ServerError(-32602, "invalid requestState");
44
+ }
45
+ }
46
+ /** Validate a retry's inputResponses shape; unknown keys are ignored by design. */
47
+ export function readInputResponses(params) {
48
+ const responses = params.inputResponses;
49
+ if (responses === undefined)
50
+ return undefined;
51
+ if (typeof responses !== "object" || responses === null || Array.isArray(responses)) {
52
+ throw new ServerError(-32602, "inputResponses must be an object");
53
+ }
54
+ return responses;
55
+ }
@@ -0,0 +1,21 @@
1
+ import { type Obj } from "../server-events/index.js";
2
+ export declare const PROTOCOL_VERSION = "2026-07-28";
3
+ export interface CacheHints {
4
+ /** Freshness hint in milliseconds; 0 means immediately stale. */
5
+ readonly ttlMs: number;
6
+ readonly cacheScope: "public" | "private";
7
+ }
8
+ export declare const DEFAULT_CACHE_HINTS: CacheHints;
9
+ /** Ordinary complete result, with optional CacheableResult fields. */
10
+ export declare function complete(result: Obj, cache?: CacheHints): Obj;
11
+ export interface Page<T> {
12
+ readonly items: readonly T[];
13
+ readonly nextCursor?: string;
14
+ }
15
+ /**
16
+ * Offset-based opaque server cursors. Input order must be deterministic;
17
+ * clients never see or parse the offset. Invalid cursors are -32602.
18
+ */
19
+ export declare function paginate<T>(items: readonly T[], cursor: unknown, pageSize?: number): Page<T>;
20
+ /** Validate the stateless per-request metadata required on every request. */
21
+ export declare function validateRequestMeta(params: Obj | undefined, supportedVersions?: readonly string[]): void;
@@ -0,0 +1,49 @@
1
+ import { ServerError } from "../server-events/index.js";
2
+ export const PROTOCOL_VERSION = "2026-07-28";
3
+ export const DEFAULT_CACHE_HINTS = { ttlMs: 0, cacheScope: "private" };
4
+ /** Ordinary complete result, with optional CacheableResult fields. */
5
+ export function complete(result, cache) {
6
+ return {
7
+ resultType: "complete",
8
+ ...result,
9
+ ...(cache !== undefined ? { ttlMs: cache.ttlMs, cacheScope: cache.cacheScope } : {}),
10
+ };
11
+ }
12
+ /**
13
+ * Offset-based opaque server cursors. Input order must be deterministic;
14
+ * clients never see or parse the offset. Invalid cursors are -32602.
15
+ */
16
+ export function paginate(items, cursor, pageSize = 100) {
17
+ let offset = 0;
18
+ if (cursor !== undefined && cursor !== null) {
19
+ if (typeof cursor !== "string" || !/^\d+$/u.test(cursor))
20
+ throw new ServerError(-32602, "invalid cursor");
21
+ offset = Number.parseInt(cursor, 10);
22
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > items.length) {
23
+ throw new ServerError(-32602, "invalid cursor");
24
+ }
25
+ }
26
+ const page = items.slice(offset, offset + pageSize);
27
+ return {
28
+ items: page,
29
+ ...(offset + pageSize < items.length ? { nextCursor: String(offset + pageSize) } : {}),
30
+ };
31
+ }
32
+ /** Validate the stateless per-request metadata required on every request. */
33
+ export function validateRequestMeta(params, supportedVersions = [PROTOCOL_VERSION]) {
34
+ const meta = params?.["_meta"];
35
+ if (typeof meta !== "object" || meta === null || Array.isArray(meta)) {
36
+ throw new ServerError(-32602, "missing required _meta");
37
+ }
38
+ const version = meta["io.modelcontextprotocol/protocolVersion"];
39
+ if (typeof version !== "string" || !supportedVersions.includes(version)) {
40
+ throw new ServerError(-32022, "unsupported protocol version", {
41
+ requested: typeof version === "string" ? version : undefined,
42
+ supported: supportedVersions,
43
+ });
44
+ }
45
+ const capabilities = meta["io.modelcontextprotocol/clientCapabilities"];
46
+ if (typeof capabilities !== "object" || capabilities === null || Array.isArray(capabilities)) {
47
+ throw new ServerError(-32602, "missing io.modelcontextprotocol/clientCapabilities");
48
+ }
49
+ }
@@ -0,0 +1,91 @@
1
+ import type { JsonRpcRequest } from "../core/index.js";
2
+ import { type SchemaValidator } from "../ops/index.js";
3
+ import { EventsServer, SubscriptionsServer, TaskCenter, type Obj } from "../server-events/index.js";
4
+ import { type CacheHints } from "./protocol.js";
5
+ export interface ToolDefinition {
6
+ readonly name: string;
7
+ readonly description?: string;
8
+ readonly inputSchema?: Obj;
9
+ readonly outputSchema?: Obj;
10
+ readonly annotations?: Obj;
11
+ readonly handler: (args: unknown) => unknown | Promise<unknown>;
12
+ }
13
+ export interface ResourceDefinition {
14
+ readonly uri: string;
15
+ readonly name: string;
16
+ readonly description?: string;
17
+ readonly mimeType?: string;
18
+ readonly handler: () => unknown | Promise<unknown>;
19
+ }
20
+ export interface ResourceTemplateDefinition {
21
+ readonly uriTemplate: string;
22
+ readonly name: string;
23
+ readonly description?: string;
24
+ readonly mimeType?: string;
25
+ readonly handler: (uri: string, vars: Record<string, string>) => unknown | Promise<unknown>;
26
+ }
27
+ export interface PromptDefinition {
28
+ readonly name: string;
29
+ readonly description?: string;
30
+ readonly arguments?: ReadonlyArray<{
31
+ readonly name: string;
32
+ readonly description?: string;
33
+ readonly required?: boolean;
34
+ }>;
35
+ readonly handler: (args: Record<string, string>) => unknown | Promise<unknown>;
36
+ }
37
+ export type CompletionHandler = (input: {
38
+ readonly ref: Obj;
39
+ readonly argument: {
40
+ readonly name: string;
41
+ readonly value: string;
42
+ };
43
+ readonly context?: Obj;
44
+ }) => {
45
+ readonly values: string[];
46
+ readonly total?: number;
47
+ readonly hasMore?: boolean;
48
+ } | Promise<{
49
+ readonly values: string[];
50
+ readonly total?: number;
51
+ readonly hasMore?: boolean;
52
+ }>;
53
+ export interface McpServerOptions {
54
+ readonly serverInfo: {
55
+ readonly name: string;
56
+ readonly version: string;
57
+ readonly title?: string;
58
+ };
59
+ readonly instructions?: string;
60
+ readonly supportedVersions?: readonly string[];
61
+ readonly cache?: CacheHints;
62
+ readonly pageSize?: number;
63
+ readonly validator?: SchemaValidator;
64
+ readonly subscriptions?: SubscriptionsServer;
65
+ readonly events?: EventsServer;
66
+ readonly tasks?: TaskCenter;
67
+ readonly onComplete?: CompletionHandler;
68
+ }
69
+ /** Wrap a TaskCenter state as a task-handle result (resultType "task"). */
70
+ export declare function taskResult(state: Obj): Obj;
71
+ /**
72
+ * Transport-agnostic MCP 2026-07-28 server for the ordinary request surface:
73
+ * server/discover, tools, resources/templates, prompts, and completion.
74
+ * Push streams live in @mcp-client/server-events; the host owns JSON-RPC
75
+ * dispatch, error mapping, and transports.
76
+ */
77
+ export declare class McpServer {
78
+ #private;
79
+ constructor(options: McpServerOptions);
80
+ registerTool(def: ToolDefinition): this;
81
+ registerResource(def: ResourceDefinition): this;
82
+ registerResourceTemplate(def: ResourceTemplateDefinition): this;
83
+ registerPrompt(def: PromptDefinition): this;
84
+ get events(): EventsServer | undefined;
85
+ get subscriptions(): SubscriptionsServer | undefined;
86
+ get tasks(): TaskCenter | undefined;
87
+ capabilities(): Obj;
88
+ discover(): Obj;
89
+ /** Handle one ordinary JSON-RPC request; throws ServerError for the host to map. */
90
+ handleRequest(msg: JsonRpcRequest): Promise<Obj>;
91
+ }
@@ -0,0 +1,314 @@
1
+ import { createBuiltinValidator } from "../ops/index.js";
2
+ import { EventsServer, ServerError, SubscriptionsServer, TaskCenter, } from "../server-events/index.js";
3
+ import { complete, DEFAULT_CACHE_HINTS, paginate, PROTOCOL_VERSION, validateRequestMeta } from "./protocol.js";
4
+ import { matchUriTemplate } from "./uri.js";
5
+ /** Wrap a TaskCenter state as a task-handle result (resultType "task"). */
6
+ export function taskResult(state) {
7
+ return { resultType: "task", ...state };
8
+ }
9
+ /**
10
+ * Transport-agnostic MCP 2026-07-28 server for the ordinary request surface:
11
+ * server/discover, tools, resources/templates, prompts, and completion.
12
+ * Push streams live in @mcp-client/server-events; the host owns JSON-RPC
13
+ * dispatch, error mapping, and transports.
14
+ */
15
+ export class McpServer {
16
+ #options;
17
+ #validator;
18
+ #tools = new Map();
19
+ #resources = new Map();
20
+ #templates = new Map();
21
+ #prompts = new Map();
22
+ #compiled = new Map();
23
+ #versions;
24
+ constructor(options) {
25
+ this.#options = options;
26
+ this.#validator = options.validator ?? createBuiltinValidator();
27
+ this.#versions = options.supportedVersions ?? [PROTOCOL_VERSION];
28
+ }
29
+ registerTool(def) {
30
+ if (!def.name)
31
+ throw new ServerError(-32602, "tool name required");
32
+ const schema = def.inputSchema ?? { type: "object", properties: {} };
33
+ if (schema.type !== "object")
34
+ throw new ServerError(-32602, `tool ${def.name}: inputSchema must be type object`);
35
+ this.#compiled.set(def.name, this.#validator.compile(schema));
36
+ this.#tools.set(def.name, def);
37
+ this.#options.subscriptions?.notifyToolsChanged();
38
+ return this;
39
+ }
40
+ registerResource(def) {
41
+ this.#resources.set(def.uri, def);
42
+ this.#options.subscriptions?.notifyResourcesChanged();
43
+ return this;
44
+ }
45
+ registerResourceTemplate(def) {
46
+ this.#templates.set(def.uriTemplate, def);
47
+ this.#options.subscriptions?.notifyResourcesChanged();
48
+ return this;
49
+ }
50
+ registerPrompt(def) {
51
+ this.#prompts.set(def.name, def);
52
+ this.#options.subscriptions?.notifyPromptsChanged();
53
+ return this;
54
+ }
55
+ get events() {
56
+ return this.#options.events;
57
+ }
58
+ get subscriptions() {
59
+ return this.#options.subscriptions;
60
+ }
61
+ get tasks() {
62
+ return this.#options.tasks;
63
+ }
64
+ capabilities() {
65
+ const caps = {};
66
+ const listChanged = this.#options.subscriptions !== undefined;
67
+ if (this.#tools.size > 0)
68
+ caps.tools = listChanged ? { listChanged: true } : {};
69
+ if (this.#resources.size > 0 || this.#templates.size > 0) {
70
+ caps.resources = listChanged ? { listChanged: true, subscribe: true } : {};
71
+ }
72
+ if (this.#prompts.size > 0)
73
+ caps.prompts = listChanged ? { listChanged: true } : {};
74
+ if (this.#options.onComplete)
75
+ caps.completions = {};
76
+ const extensions = {
77
+ ...this.#options.events?.capabilities().extensions,
78
+ ...this.#options.tasks?.capabilities().extensions,
79
+ };
80
+ if (Object.keys(extensions).length > 0)
81
+ caps.extensions = extensions;
82
+ return caps;
83
+ }
84
+ discover() {
85
+ return complete({
86
+ supportedVersions: [...this.#versions],
87
+ capabilities: this.capabilities(),
88
+ serverInfo: this.#options.serverInfo,
89
+ ...(this.#options.instructions !== undefined ? { instructions: this.#options.instructions } : {}),
90
+ }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
91
+ }
92
+ /** Handle one ordinary JSON-RPC request; throws ServerError for the host to map. */
93
+ async handleRequest(msg) {
94
+ const params = (msg.params ?? {});
95
+ validateRequestMeta(params, this.#versions);
96
+ switch (msg.method) {
97
+ case "server/discover":
98
+ return this.discover();
99
+ case "tools/list": {
100
+ const tools = [...this.#tools.values()].sort((a, b) => a.name.localeCompare(b.name));
101
+ const page = paginate(tools, params.cursor, this.#options.pageSize);
102
+ return complete({
103
+ tools: page.items.map((tool) => this.#toolSchema(tool)),
104
+ ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
105
+ }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
106
+ }
107
+ case "tools/call":
108
+ return this.#callTool(params);
109
+ case "resources/list": {
110
+ const resources = [...this.#resources.values()].sort((a, b) => a.uri.localeCompare(b.uri));
111
+ const page = paginate(resources, params.cursor, this.#options.pageSize);
112
+ return complete({
113
+ resources: page.items.map((r) => this.#resourceSchema(r)),
114
+ ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
115
+ }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
116
+ }
117
+ case "resources/templates/list": {
118
+ const templates = [...this.#templates.values()].sort((a, b) => a.uriTemplate.localeCompare(b.uriTemplate));
119
+ const page = paginate(templates, params.cursor, this.#options.pageSize);
120
+ return complete({
121
+ resourceTemplates: page.items.map((t) => ({
122
+ uriTemplate: t.uriTemplate,
123
+ name: t.name,
124
+ ...(t.description !== undefined ? { description: t.description } : {}),
125
+ ...(t.mimeType !== undefined ? { mimeType: t.mimeType } : {}),
126
+ })),
127
+ ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
128
+ }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
129
+ }
130
+ case "resources/read":
131
+ return this.#readResource(params);
132
+ case "prompts/list": {
133
+ const prompts = [...this.#prompts.values()].sort((a, b) => a.name.localeCompare(b.name));
134
+ const page = paginate(prompts, params.cursor, this.#options.pageSize);
135
+ return complete({
136
+ prompts: page.items.map((p) => ({
137
+ name: p.name,
138
+ ...(p.description !== undefined ? { description: p.description } : {}),
139
+ ...(p.arguments !== undefined ? { arguments: p.arguments } : {}),
140
+ })),
141
+ ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
142
+ }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
143
+ }
144
+ case "prompts/get":
145
+ return this.#getPrompt(params);
146
+ case "completion/complete":
147
+ return this.#complete(params);
148
+ case "events/list":
149
+ return this.#events().list();
150
+ case "events/poll":
151
+ return this.#events().poll(params);
152
+ case "tasks/get":
153
+ return this.#tasks().get(params);
154
+ case "tasks/cancel":
155
+ return this.#tasks().cancel(params);
156
+ case "tasks/update":
157
+ return this.#tasks().update(params);
158
+ case "subscriptions/listen":
159
+ case "events/stream":
160
+ throw new ServerError(-32601, `${msg.method} requires a PushChannel from the host transport`);
161
+ default:
162
+ throw new ServerError(-32601, `method not found: ${msg.method}`);
163
+ }
164
+ }
165
+ #events() {
166
+ if (!this.#options.events)
167
+ throw new ServerError(-32601, "events extension unavailable");
168
+ return this.#options.events;
169
+ }
170
+ #tasks() {
171
+ if (!this.#options.tasks)
172
+ throw new ServerError(-32601, "tasks extension unavailable");
173
+ return this.#options.tasks;
174
+ }
175
+ #toolSchema(tool) {
176
+ return {
177
+ name: tool.name,
178
+ ...(tool.description !== undefined ? { description: tool.description } : {}),
179
+ inputSchema: tool.inputSchema ?? { type: "object", properties: {} },
180
+ ...(tool.outputSchema !== undefined ? { outputSchema: tool.outputSchema } : {}),
181
+ ...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),
182
+ };
183
+ }
184
+ #resourceSchema(resource) {
185
+ return {
186
+ uri: resource.uri,
187
+ name: resource.name,
188
+ ...(resource.description !== undefined ? { description: resource.description } : {}),
189
+ ...(resource.mimeType !== undefined ? { mimeType: resource.mimeType } : {}),
190
+ };
191
+ }
192
+ async #callTool(params) {
193
+ const name = params.name;
194
+ if (typeof name !== "string")
195
+ throw new ServerError(-32602, "tool name required");
196
+ const tool = this.#tools.get(name);
197
+ if (!tool)
198
+ throw new ServerError(-32602, `unknown tool: ${name}`);
199
+ const compiled = this.#compiled.get(name);
200
+ if (compiled && !compiled.ok)
201
+ throw new ServerError(-32603, `tool ${name}: ${compiled.message}`);
202
+ const args = params.arguments ?? {};
203
+ if (compiled?.ok) {
204
+ const verdict = compiled.validate(args);
205
+ if (!verdict.valid)
206
+ throw new ServerError(-32602, `invalid tool arguments: ${verdict.errors[0]?.message ?? "schema mismatch"}`, { issues: verdict.errors });
207
+ }
208
+ let returned;
209
+ try {
210
+ returned = await tool.handler(args);
211
+ }
212
+ catch (error) {
213
+ return complete({
214
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
215
+ isError: true,
216
+ });
217
+ }
218
+ if (typeof returned === "object" && returned !== null && "resultType" in returned)
219
+ return returned;
220
+ const result = normalizeToolResult(returned);
221
+ if (tool.outputSchema && result.structuredContent !== undefined) {
222
+ const output = this.#validator.compile(tool.outputSchema);
223
+ if (!output.ok)
224
+ throw new ServerError(-32603, `tool ${name}: ${output.message}`);
225
+ const verdict = output.validate(result.structuredContent);
226
+ if (!verdict.valid)
227
+ throw new ServerError(-32603, `tool ${name}: output does not match outputSchema`, { issues: verdict.errors });
228
+ }
229
+ return complete(result);
230
+ }
231
+ async #readResource(params) {
232
+ const uri = params.uri;
233
+ if (typeof uri !== "string")
234
+ throw new ServerError(-32602, "resource uri required");
235
+ const exact = this.#resources.get(uri);
236
+ if (exact) {
237
+ return complete({ contents: await resourceContents(uri, exact.mimeType, await exact.handler()) }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
238
+ }
239
+ for (const template of this.#templates.values()) {
240
+ const vars = matchUriTemplate(template.uriTemplate, uri);
241
+ if (vars) {
242
+ return complete({ contents: await resourceContents(uri, template.mimeType, await template.handler(uri, vars)) }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
243
+ }
244
+ }
245
+ throw new ServerError(-32602, `resource not found: ${uri}`);
246
+ }
247
+ async #getPrompt(params) {
248
+ const name = params.name;
249
+ if (typeof name !== "string")
250
+ throw new ServerError(-32602, "prompt name required");
251
+ const prompt = this.#prompts.get(name);
252
+ if (!prompt)
253
+ throw new ServerError(-32602, `unknown prompt: ${name}`);
254
+ const args = params.arguments ?? {};
255
+ if (typeof args !== "object" || args === null || Array.isArray(args))
256
+ throw new ServerError(-32602, "prompt arguments must be an object");
257
+ for (const arg of prompt.arguments ?? []) {
258
+ if (arg.required === true && typeof args[arg.name] !== "string") {
259
+ throw new ServerError(-32602, `missing required prompt argument: ${arg.name}`);
260
+ }
261
+ }
262
+ const returned = await prompt.handler(args);
263
+ const result = Array.isArray(returned) ? { messages: returned } : returned;
264
+ if (typeof result !== "object" || result === null || !Array.isArray(result.messages)) {
265
+ throw new ServerError(-32603, `prompt ${name}: handler must return messages`);
266
+ }
267
+ return complete(result);
268
+ }
269
+ async #complete(params) {
270
+ const handler = this.#options.onComplete;
271
+ if (!handler)
272
+ throw new ServerError(-32601, "completion unavailable");
273
+ const argument = params.argument;
274
+ if (typeof argument !== "object" || argument === null || typeof argument.name !== "string" || typeof argument.value !== "string") {
275
+ throw new ServerError(-32602, "completion argument.name/value required");
276
+ }
277
+ const ref = params.ref;
278
+ if (typeof ref !== "object" || ref === null)
279
+ throw new ServerError(-32602, "completion ref required");
280
+ const result = await handler({
281
+ ref: ref,
282
+ argument: argument,
283
+ ...(params.context !== undefined ? { context: params.context } : {}),
284
+ });
285
+ const values = result.values.slice(0, 100);
286
+ return complete({
287
+ completion: {
288
+ values,
289
+ ...(result.total !== undefined ? { total: result.total } : {}),
290
+ ...(result.hasMore !== undefined || result.values.length > 100 ? { hasMore: result.hasMore ?? true } : {}),
291
+ },
292
+ });
293
+ }
294
+ }
295
+ function normalizeToolResult(returned) {
296
+ if (typeof returned === "object" && returned !== null && Array.isArray(returned.content))
297
+ return returned;
298
+ return { content: [{ type: "text", text: typeof returned === "string" ? returned : JSON.stringify(returned) }] };
299
+ }
300
+ async function resourceContents(uri, mimeType, returned) {
301
+ const entries = Array.isArray(returned) ? returned : [returned];
302
+ return entries.map((entry) => {
303
+ if (typeof entry === "string")
304
+ return { uri, text: entry, ...(mimeType !== undefined ? { mimeType } : {}) };
305
+ if (typeof entry !== "object" || entry === null)
306
+ throw new ServerError(-32603, "resource handler returned invalid contents");
307
+ const obj = entry;
308
+ const hasText = "text" in obj;
309
+ const hasBlob = "blob" in obj;
310
+ if (hasText === hasBlob)
311
+ throw new ServerError(-32603, "resource contents need exactly one of text/blob");
312
+ return { uri, ...obj, ...(mimeType !== undefined && obj.mimeType === undefined ? { mimeType } : {}) };
313
+ });
314
+ }
@@ -0,0 +1,2 @@
1
+ /** RFC 6570 subset matcher for resource reads: {var} and {+var} expressions. */
2
+ export declare function matchUriTemplate(template: string, uri: string): Record<string, string> | undefined;
@@ -0,0 +1,27 @@
1
+ /** RFC 6570 subset matcher for resource reads: {var} and {+var} expressions. */
2
+ export function matchUriTemplate(template, uri) {
3
+ const vars = [];
4
+ let pattern = "";
5
+ for (let i = 0; i < template.length; i++) {
6
+ const ch = template[i];
7
+ if (ch === "{") {
8
+ const end = template.indexOf("}", i);
9
+ if (end < 0)
10
+ return undefined;
11
+ const expr = template.slice(i + 1, end);
12
+ if (/^[+]?[A-Za-z_][A-Za-z0-9_]*$/u.test(expr) === false)
13
+ return undefined;
14
+ const plus = expr.startsWith("+");
15
+ vars.push(plus ? expr.slice(1) : expr);
16
+ pattern += plus ? "(.+)" : "([^/]+)";
17
+ i = end;
18
+ }
19
+ else {
20
+ pattern += ch.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
21
+ }
22
+ }
23
+ const match = new RegExp(`^${pattern}$`, "u").exec(uri);
24
+ if (!match)
25
+ return undefined;
26
+ return Object.fromEntries(vars.map((name, i) => [name, decodeURIComponent(match[i + 1])]));
27
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jangmanj/mcp-client",
3
- "version": "0.8.0",
4
- "description": "MCP 2026-07-28 client library: push events/subscriptions, core, transports, auth, ops, MRTR/cache, OTEL telemetry, and extensions.",
3
+ "version": "0.9.0",
4
+ "description": "MCP 2026-07-28 client and server library: push events/subscriptions, core, transports, auth, ops, MRTR/cache, OTEL telemetry, and extensions.",
5
5
  "license": "MIT",
6
6
  "author": "JangMan-J",
7
7
  "keywords": [
@@ -56,6 +56,10 @@
56
56
  "types": "./dist/server-events/index.d.ts",
57
57
  "default": "./dist/server-events/index.js"
58
58
  },
59
+ "./server": {
60
+ "types": "./dist/server/index.d.ts",
61
+ "default": "./dist/server/index.js"
62
+ },
59
63
  "./auth": {
60
64
  "types": "./dist/auth/index.d.ts",
61
65
  "default": "./dist/auth/index.js"