@tsed/platform-mcp 8.35.0 → 8.36.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.
@@ -1,15 +1,17 @@
1
1
  import type { ReadResourceCallback, ResourceMetadata, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { ReadResourceResult } from "@modelcontextprotocol/sdk/types.js";
2
3
  import { type TokenProvider } from "@tsed/di";
3
4
  type ResourceMetadataProps = ResourceMetadata & {
4
5
  name: string;
5
6
  };
7
+ export type ResourceCallback = (...args: Parameters<ReadResourceCallback>) => ReadResourceResult | Record<string, unknown> | Promise<ReadResourceResult | Record<string, unknown>>;
6
8
  export type FnResourceReadProps = ResourceMetadataProps & {
7
9
  uri: string;
8
- handler: ReadResourceCallback;
10
+ handler: ResourceCallback;
9
11
  };
10
12
  export type FnResourceTemplateProps = ResourceMetadataProps & {
11
13
  template: ResourceTemplate;
12
- handler: ReadResourceCallback;
14
+ handler: ResourceCallback;
13
15
  };
14
16
  type ClassResourceBaseProps = Omit<ResourceMetadataProps, "name"> & {
15
17
  name?: string;
@@ -31,7 +33,7 @@ export type ClassResourceTemplateProps = ClassResourceBaseProps & {
31
33
  export type ResourceProps = FnResourceReadProps | FnResourceTemplateProps | ClassResourceReadProps | ClassResourceTemplateProps;
32
34
  declare function mapOptions(options: ResourceProps): {
33
35
  name: string | undefined;
34
- handler: ReadResourceCallback;
36
+ handler: ResourceCallback;
35
37
  _meta?: {
36
38
  [x: string]: unknown;
37
39
  } | undefined;
@@ -53,7 +55,7 @@ declare function mapOptions(options: ResourceProps): {
53
55
  uri: string;
54
56
  } | {
55
57
  name: string | undefined;
56
- handler: ReadResourceCallback;
58
+ handler: ResourceCallback;
57
59
  _meta?: {
58
60
  [x: string]: unknown;
59
61
  } | undefined;
@@ -75,7 +77,7 @@ declare function mapOptions(options: ResourceProps): {
75
77
  template: ResourceTemplate;
76
78
  } | {
77
79
  name: string | undefined;
78
- handler: ReadResourceCallback;
80
+ handler: ResourceCallback;
79
81
  _meta?: {
80
82
  [x: string]: unknown;
81
83
  } | undefined;
@@ -99,7 +101,7 @@ declare function mapOptions(options: ResourceProps): {
99
101
  uri: string;
100
102
  } | {
101
103
  name: string | undefined;
102
- handler: ReadResourceCallback;
104
+ handler: ResourceCallback;
103
105
  _meta?: {
104
106
  [x: string]: unknown;
105
107
  } | undefined;
@@ -10,20 +10,20 @@ import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/proto
10
10
  * @module platform/mcp
11
11
  * @since 8.17.0
12
12
  */
13
- export type ToolCallback<Args = undefined> = (args: Args, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => CallToolResult | Promise<CallToolResult>;
13
+ export type ToolCallback<Args = undefined, Output = unknown> = (args: Args, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => CallToolResult | Promise<CallToolResult> | Output | Promise<Output>;
14
14
  type BaseToolConfig = {
15
15
  title?: string;
16
16
  description?: string;
17
17
  annotations?: ToolAnnotations;
18
18
  _meta?: Record<string, unknown>;
19
19
  };
20
- type BaseToolProps<Input, Output = undefined> = BaseToolConfig & {
20
+ type BaseToolProps<Input, Output = unknown> = BaseToolConfig & {
21
21
  inputSchema?: JsonSchema<Input> | (() => JsonSchema<Input>) | Tool["inputSchema"];
22
22
  outputSchema?: JsonSchema<Output> | Tool["outputSchema"];
23
23
  };
24
- export type FnToolProps<Input, Output = undefined> = BaseToolProps<Input, Output> & {
24
+ export type FnToolProps<Input, Output = unknown> = BaseToolProps<Input, Output> & {
25
25
  name: string;
26
- handler: ToolCallback<Input>;
26
+ handler: ToolCallback<Input, Output>;
27
27
  };
28
28
  /**
29
29
  * Configuration accepted when decorating class methods as MCP tools.
@@ -31,7 +31,7 @@ export type FnToolProps<Input, Output = undefined> = BaseToolProps<Input, Output
31
31
  * @module platform/mcp
32
32
  * @since 8.17.0
33
33
  */
34
- export type ClassToolProps<Input, Output = undefined> = BaseToolProps<Input, Output> & {
34
+ export type ClassToolProps<Input, Output = unknown> = BaseToolProps<Input, Output> & {
35
35
  name?: string;
36
36
  token: Type | AbstractType<any>;
37
37
  propertyKey: string | symbol;
@@ -42,7 +42,7 @@ export type ClassToolProps<Input, Output = undefined> = BaseToolProps<Input, Out
42
42
  * @module platform/mcp
43
43
  * @since 8.17.0
44
44
  */
45
- export type ToolProps<Input, Output = undefined> = FnToolProps<Input, Output> | ClassToolProps<Input, Output>;
45
+ export type ToolProps<Input, Output = unknown> = FnToolProps<Input, Output> | ClassToolProps<Input, Output>;
46
46
  /**
47
47
  * Registers an MCP tool provider and wraps its handler with error logging plus schema conversion.
48
48
  *
@@ -61,6 +61,6 @@ export type ToolProps<Input, Output = undefined> = FnToolProps<Input, Output> |
61
61
  * });
62
62
  * ```
63
63
  */
64
- export declare function defineTool<Input, Output = undefined>(options: FnToolProps<Input, Output>): TokenProvider;
65
- export declare function defineTool<Input, Output = undefined>(options: ClassToolProps<Input, Output>): TokenProvider;
64
+ export declare function defineTool<Input, Output = unknown>(options: FnToolProps<Input, Output>): TokenProvider;
65
+ export declare function defineTool<Input, Output = unknown>(options: ClassToolProps<Input, Output>): TokenProvider;
66
66
  export {};
@@ -11,4 +11,6 @@ export * from "./fn/defineTool.js";
11
11
  export * from "./interfaces/PlatformMcpSettings.js";
12
12
  export * from "./services/McpServerFactory.js";
13
13
  export * from "./services/PlatformMcpModule.js";
14
+ export * from "./utils/asResourceResponse.js";
15
+ export * from "./utils/asToolResponse.js";
14
16
  export * from "./utils/toZod.js";
@@ -0,0 +1,4 @@
1
+ import { ReadResourceResult } from "@modelcontextprotocol/sdk/types.js";
2
+ export declare function asResourceResponse(uri: string, payload: Record<string, unknown> | ReadResourceResult, opts?: {
3
+ isError?: boolean;
4
+ }): ReadResourceResult;
@@ -0,0 +1,14 @@
1
+ import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
2
+ export interface StructuredResponse<T extends {
3
+ [x: string]: unknown;
4
+ } = {
5
+ [x: string]: unknown;
6
+ }> extends CallToolResult {
7
+ structuredContent?: T | undefined;
8
+ isError?: true;
9
+ }
10
+ export declare function asToolResponse<T extends {
11
+ [x: string]: unknown;
12
+ }>(payload: T | StructuredResponse, opts?: {
13
+ isError?: true;
14
+ }): StructuredResponse<T>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsed/platform-mcp",
3
- "version": "8.35.0",
3
+ "version": "8.36.0",
4
4
  "description": "Model Context Protocol integration for Ts.ED HTTP adapters.",
5
5
  "source": "./src/index.ts",
6
6
  "type": "module",
@@ -32,13 +32,13 @@
32
32
  "zod": ">=4.0.0"
33
33
  },
34
34
  "devDependencies": {
35
- "@tsed/barrels": "8.35.0",
36
- "@tsed/core": "8.35.0",
37
- "@tsed/di": "8.35.0",
38
- "@tsed/json-mapper": "8.35.0",
39
- "@tsed/platform-http": "8.35.0",
40
- "@tsed/schema": "8.35.0",
41
- "@tsed/typescript": "8.35.0",
35
+ "@tsed/barrels": "8.36.0",
36
+ "@tsed/core": "8.36.0",
37
+ "@tsed/di": "8.36.0",
38
+ "@tsed/json-mapper": "8.36.0",
39
+ "@tsed/platform-http": "8.36.0",
40
+ "@tsed/schema": "8.36.0",
41
+ "@tsed/typescript": "8.36.0",
42
42
  "typescript": "6.0.2",
43
43
  "vitest": "4.1.4"
44
44
  },
@@ -1,7 +1,7 @@
1
- import {type AbstractType, type Type, isArrowFn} from "@tsed/core";
1
+ import {type AbstractType, isArrowFn, type Type} from "@tsed/core";
2
2
  import type {GetPromptResult, ServerNotification, ServerRequest} from "@modelcontextprotocol/sdk/types.js";
3
3
  import {JsonSchema, s} from "@tsed/schema";
4
- import {type TokenProvider, context, inject, injectable, logger} from "@tsed/di";
4
+ import {context, inject, injectable, logger, type TokenProvider} from "@tsed/di";
5
5
  import {MCP_PROVIDER_TYPES} from "../constants/constants.js";
6
6
  import type {RequestHandlerExtra} from "@modelcontextprotocol/sdk/shared/protocol.js";
7
7
  import {constantCase} from "change-case";
@@ -64,7 +64,10 @@ function mapOptions<Args = any>(options: PromptProps<Args>) {
64
64
  return {
65
65
  ...options,
66
66
  name,
67
- argsSchema: toZod(isArrowFn(options.argsSchema) ? options.argsSchema() : options.argsSchema),
67
+ argsSchema: toZod(isArrowFn(options.argsSchema) ? options.argsSchema() : options.argsSchema, {
68
+ useAlias: true,
69
+ groups: [name!, "prompt"]
70
+ }),
68
71
  handler: handler
69
72
  };
70
73
  }
@@ -7,6 +7,23 @@ describe("defineResource", () => {
7
7
  beforeEach(() => PlatformTest.create());
8
8
  afterEach(() => PlatformTest.reset());
9
9
 
10
+ function expectError(result: any, error: Record<string, unknown>) {
11
+ expect(result.contents[0]).toEqual({
12
+ uri: "tsed://resource",
13
+ mimeType: "plain/text",
14
+ text: error.message
15
+ });
16
+ expect(result.contents[1]).toEqual({
17
+ uri: "tsed://resource",
18
+ mimeType: "application/json",
19
+ text: expect.any(String)
20
+ });
21
+ expect(JSON.parse(result.contents[1].text)).toEqual({
22
+ ...error,
23
+ request_id: expect.any(String)
24
+ });
25
+ }
26
+
10
27
  it("should wrap handler errors with structured MCP payloads", async () => {
11
28
  const token = defineResource({
12
29
  name: "failing-resource",
@@ -19,16 +36,11 @@ describe("defineResource", () => {
19
36
  const definition = inject<any>(token);
20
37
  const result = await definition.handler(new URL("tsed://resource"), {} as any);
21
38
 
22
- expect(result).toEqual({
23
- contents: [],
24
- _meta: {
25
- status_code: undefined,
26
- code: "E_MCP_RESOURCE_ERROR",
27
- error_name: "Error",
28
- message: "boom",
29
- request_id: expect.any(String),
30
- resource: "failing-resource"
31
- }
39
+ expectError(result, {
40
+ code: "E_MCP_RESOURCE_ERROR",
41
+ error_name: "Error",
42
+ message: "boom",
43
+ resource: "failing-resource"
32
44
  });
33
45
  });
34
46
 
@@ -47,16 +59,12 @@ describe("defineResource", () => {
47
59
  const definition = inject<any>(token);
48
60
  const result = await definition.handler(new URL("tsed://resource"), {} as any);
49
61
 
50
- expect(result).toEqual({
51
- contents: [],
52
- _meta: {
53
- status_code: 404,
54
- code: "E_MCP_RESOURCE_NOT_FOUND",
55
- error_name: "NotFound",
56
- message: "Not found",
57
- request_id: expect.any(String),
58
- resource: "http-resource"
59
- }
62
+ expectError(result, {
63
+ status_code: 404,
64
+ code: "E_MCP_RESOURCE_NOT_FOUND",
65
+ error_name: "NotFound",
66
+ message: "Not found",
67
+ resource: "http-resource"
60
68
  });
61
69
  });
62
70
 
@@ -72,16 +80,33 @@ describe("defineResource", () => {
72
80
  const definition = inject<any>(token);
73
81
  const result = await definition.handler(new URL("tsed://resource"), {} as any);
74
82
 
75
- expect(result).toEqual({
76
- contents: [],
77
- _meta: {
78
- status_code: undefined,
79
- code: "E_MCP_RESOURCE_ERROR",
80
- error_name: undefined,
81
- message: "boom",
82
- request_id: expect.any(String),
83
- resource: "primitive-error-resource"
83
+ expectError(result, {
84
+ code: "E_MCP_RESOURCE_ERROR",
85
+ message: "boom",
86
+ resource: "primitive-error-resource"
87
+ });
88
+ });
89
+
90
+ it("should normalize successful resource payloads", async () => {
91
+ const token = defineResource({
92
+ name: "resource",
93
+ uri: "tsed://resource",
94
+ handler() {
95
+ return {id: "resource-id"} as any;
84
96
  }
85
97
  });
98
+
99
+ const definition = inject<any>(token);
100
+ const result = await definition.handler(new URL("tsed://resource"), {} as any);
101
+
102
+ expect(result).toEqual({
103
+ contents: [
104
+ {
105
+ uri: "tsed://resource",
106
+ mimeType: "application/json",
107
+ text: '{\n "id": "resource-id"\n}'
108
+ }
109
+ ]
110
+ });
86
111
  });
87
112
  });
@@ -1,21 +1,27 @@
1
1
  import type {ReadResourceCallback, ResourceMetadata, ResourceTemplate} from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import {type TokenProvider, context, inject, injectable, logger} from "@tsed/di";
2
+ import type {ReadResourceResult} from "@modelcontextprotocol/sdk/types.js";
3
+ import {context, inject, injectable, logger, type TokenProvider} from "@tsed/di";
3
4
  import {MCP_PROVIDER_TYPES} from "../constants/constants.js";
4
5
  import {constantCase} from "change-case";
5
6
  import {s} from "@tsed/schema";
7
+ import {asResourceResponse} from "../utils/asResourceResponse.js";
6
8
 
7
9
  type ResourceMetadataProps = ResourceMetadata & {
8
10
  name: string;
9
11
  };
10
12
 
13
+ export type ResourceCallback = (
14
+ ...args: Parameters<ReadResourceCallback>
15
+ ) => ReadResourceResult | Record<string, unknown> | Promise<ReadResourceResult | Record<string, unknown>>;
16
+
11
17
  export type FnResourceReadProps = ResourceMetadataProps & {
12
18
  uri: string;
13
- handler: ReadResourceCallback;
19
+ handler: ResourceCallback;
14
20
  };
15
21
 
16
22
  export type FnResourceTemplateProps = ResourceMetadataProps & {
17
23
  template: ResourceTemplate;
18
- handler: ReadResourceCallback;
24
+ handler: ResourceCallback;
19
25
  };
20
26
 
21
27
  type ClassResourceBaseProps = Omit<ResourceMetadataProps, "name"> & {
@@ -45,7 +51,7 @@ function isClassResourceProps(options: ResourceProps): options is ClassResourceR
45
51
  }
46
52
 
47
53
  function mapOptions(options: ResourceProps) {
48
- let handler: ReadResourceCallback;
54
+ let handler: ResourceCallback;
49
55
  const name = options.name || ("propertyKey" in options ? String(options.propertyKey) : undefined);
50
56
 
51
57
  if (isClassResourceProps(options)) {
@@ -103,7 +109,14 @@ export function defineResource(options: ResourceProps): TokenProvider {
103
109
  ...opts,
104
110
  async handler(...args: Parameters<ReadResourceCallback>) {
105
111
  try {
106
- return await handler(...args);
112
+ const result = await handler(...args);
113
+
114
+ logger().info({
115
+ event: "MCP_TOOL_END",
116
+ tool: opts.name
117
+ });
118
+
119
+ return asResourceResponse(args[0]?.toString(), result);
107
120
  } catch (er: any) {
108
121
  const safeErr =
109
122
  er && typeof er === "object"
@@ -114,27 +127,29 @@ export function defineResource(options: ResourceProps): TokenProvider {
114
127
  status: undefined
115
128
  };
116
129
  const code = safeErr.name && safeErr.status ? `E_MCP_RESOURCE_${constantCase(safeErr.name)}` : "E_MCP_RESOURCE_ERROR";
130
+
117
131
  logger().error({
118
132
  event: "MCP_RESOURCE_ERROR",
119
133
  status_code: safeErr.status,
120
134
  code,
121
135
  error_name: safeErr.name,
122
136
  message: safeErr.message,
123
- request_id: context().id,
124
137
  resource: opts.name
125
138
  });
126
139
 
127
- return {
128
- contents: [],
129
- _meta: {
140
+ return asResourceResponse(
141
+ args[0]?.toString(),
142
+ {
130
143
  status_code: safeErr.status,
131
144
  code,
132
145
  error_name: safeErr.name,
133
146
  message: safeErr.message,
134
147
  request_id: context().id,
135
148
  resource: opts.name
136
- }
137
- };
149
+ },
150
+ {isError: true}
151
+ );
152
+ } finally {
138
153
  }
139
154
  }
140
155
  };
@@ -1,4 +1,4 @@
1
- import {Default, JsonSchema, Name, Property, from} from "@tsed/schema";
1
+ import {Default, from, JsonSchema, Name, Property, s, string} from "@tsed/schema";
2
2
  import {afterEach, beforeEach, describe, expect, it} from "vitest";
3
3
  import {PlatformTest} from "@tsed/platform-http/testing";
4
4
  import {defineTool} from "./defineTool.js";
@@ -39,11 +39,10 @@ describe("defineTool", () => {
39
39
 
40
40
  const result = await definition.handler({}, {} as any);
41
41
 
42
+ expect(result.isError).toBe(true);
42
43
  expect(result.structuredContent).toEqual({
43
- status_code: undefined,
44
44
  code: "E_MCP_TOOL_ERROR",
45
45
  message: "boom",
46
- request_id: expect.any(String),
47
46
  tool: "failing-tool"
48
47
  });
49
48
  });
@@ -62,11 +61,11 @@ describe("defineTool", () => {
62
61
  const definition = inject<any>(token);
63
62
  const result = await definition.handler({}, {} as any);
64
63
 
64
+ expect(result.isError).toBe(true);
65
65
  expect(result.structuredContent).toEqual({
66
66
  status_code: 404,
67
67
  code: "E_MCP_TOOL_NOT_FOUND",
68
68
  message: "Not found",
69
- request_id: expect.any(String),
70
69
  tool: "http-tool"
71
70
  });
72
71
  });
@@ -103,6 +102,28 @@ describe("defineTool", () => {
103
102
  });
104
103
  });
105
104
 
105
+ it("should expose aliases declared by functional output schemas", () => {
106
+ const token = defineTool({
107
+ name: "aliased-tool-output",
108
+ outputSchema: s.object({prop: string().required()}).addAlias("prop", "aliasProp"),
109
+ handler() {
110
+ return {prop: "value"};
111
+ }
112
+ });
113
+
114
+ const definition = inject<any>(token);
115
+
116
+ expect(definition.outputSchema.toJSONSchema()).toMatchObject({
117
+ type: "object",
118
+ properties: {
119
+ aliasProp: {
120
+ type: "string"
121
+ }
122
+ },
123
+ required: ["aliasProp"]
124
+ });
125
+ });
126
+
106
127
  it("should deserialize functional tool input from a Ts.ED model schema", async () => {
107
128
  const token = defineTool<KnowledgeSearchRequest>({
108
129
  name: "knowledge-search",
@@ -128,4 +149,26 @@ describe("defineTool", () => {
128
149
  {} as any
129
150
  );
130
151
  });
152
+
153
+ it("should normalize successful tool payloads as structured content", async () => {
154
+ const token = defineTool({
155
+ name: "successful-tool",
156
+ outputSchema: s.object({id: string()}),
157
+ handler() {
158
+ return {id: "tool-id"};
159
+ }
160
+ });
161
+
162
+ const definition = inject<any>(token);
163
+
164
+ await expect(definition.handler({}, {} as any)).resolves.toEqual({
165
+ content: [
166
+ {
167
+ type: "text",
168
+ text: '{\n "id": "tool-id"\n}'
169
+ }
170
+ ],
171
+ structuredContent: {id: "tool-id"}
172
+ });
173
+ });
131
174
  });
@@ -1,12 +1,13 @@
1
- import {type AbstractType, type Type, isArrowFn, isClass} from "@tsed/core";
1
+ import {type AbstractType, isArrowFn, isClass, type Type} from "@tsed/core";
2
2
  import type {CallToolResult, ServerNotification, ServerRequest, Tool, ToolAnnotations} from "@modelcontextprotocol/sdk/types.js";
3
3
  import {JsonEntityStore, JsonMethodStore, JsonSchema, s} from "@tsed/schema";
4
- import {type TokenProvider, context, inject, injectable, logger} from "@tsed/di";
4
+ import {context, inject, injectable, logger, type TokenProvider} from "@tsed/di";
5
5
  import {MCP_PROVIDER_TYPES} from "../constants/constants.js";
6
6
  import type {RequestHandlerExtra} from "@modelcontextprotocol/sdk/shared/protocol.js";
7
7
  import {constantCase} from "change-case";
8
8
  import {deserialize} from "@tsed/json-mapper";
9
9
  import {toZod} from "../utils/toZod.js";
10
+ import {asToolResponse} from "../utils/asToolResponse.js";
10
11
 
11
12
  /**
12
13
  * Signature implemented by MCP tool handlers invoked through {@link defineTool}.
@@ -15,10 +16,10 @@ import {toZod} from "../utils/toZod.js";
15
16
  * @module platform/mcp
16
17
  * @since 8.17.0
17
18
  */
18
- export type ToolCallback<Args = undefined> = (
19
+ export type ToolCallback<Args = undefined, Output = unknown> = (
19
20
  args: Args,
20
21
  extra: RequestHandlerExtra<ServerRequest, ServerNotification>
21
- ) => CallToolResult | Promise<CallToolResult>;
22
+ ) => CallToolResult | Promise<CallToolResult> | Output | Promise<Output>;
22
23
 
23
24
  type BaseToolConfig = {
24
25
  title?: string;
@@ -27,14 +28,14 @@ type BaseToolConfig = {
27
28
  _meta?: Record<string, unknown>;
28
29
  };
29
30
 
30
- type BaseToolProps<Input, Output = undefined> = BaseToolConfig & {
31
+ type BaseToolProps<Input, Output = unknown> = BaseToolConfig & {
31
32
  inputSchema?: JsonSchema<Input> | (() => JsonSchema<Input>) | Tool["inputSchema"];
32
33
  outputSchema?: JsonSchema<Output> | Tool["outputSchema"];
33
34
  };
34
35
 
35
- export type FnToolProps<Input, Output = undefined> = BaseToolProps<Input, Output> & {
36
+ export type FnToolProps<Input, Output = unknown> = BaseToolProps<Input, Output> & {
36
37
  name: string;
37
- handler: ToolCallback<Input>;
38
+ handler: ToolCallback<Input, Output>;
38
39
  };
39
40
 
40
41
  /**
@@ -43,7 +44,7 @@ export type FnToolProps<Input, Output = undefined> = BaseToolProps<Input, Output
43
44
  * @module platform/mcp
44
45
  * @since 8.17.0
45
46
  */
46
- export type ClassToolProps<Input, Output = undefined> = BaseToolProps<Input, Output> & {
47
+ export type ClassToolProps<Input, Output = unknown> = BaseToolProps<Input, Output> & {
47
48
  name?: string;
48
49
  token: Type | AbstractType<any>;
49
50
  propertyKey: string | symbol;
@@ -55,11 +56,12 @@ export type ClassToolProps<Input, Output = undefined> = BaseToolProps<Input, Out
55
56
  * @module platform/mcp
56
57
  * @since 8.17.0
57
58
  */
58
- export type ToolProps<Input, Output = undefined> = FnToolProps<Input, Output> | ClassToolProps<Input, Output>;
59
+ export type ToolProps<Input, Output = unknown> = FnToolProps<Input, Output> | ClassToolProps<Input, Output>;
59
60
 
60
- type MappedToolOptions<Input, Output = undefined> = Omit<ToolProps<Input, Output>, "token" | "propertyKey"> & {
61
- handler: ToolCallback<Input>;
61
+ type MappedToolOptions<Input, Output = unknown> = Omit<ToolProps<Input, Output>, "token" | "propertyKey"> & {
62
+ handler: ToolCallback<Input, Output>;
62
63
  inputStore?: JsonEntityStore;
64
+ outputStore?: JsonMethodStore;
63
65
  };
64
66
 
65
67
  function getOutputSchema<Output>(methodStore: JsonMethodStore): JsonSchema<Output> {
@@ -94,8 +96,8 @@ function deserializeInput<Input>(args: Input, inputSchema: unknown, inputStore?:
94
96
  }) as Input;
95
97
  }
96
98
 
97
- function mapOptions<Input, Output = undefined>(options: ToolProps<Input, Output>): MappedToolOptions<Input, Output> {
98
- let handler: ToolCallback<Input>;
99
+ function mapOptions<Input, Output = unknown>(options: ToolProps<Input, Output>): MappedToolOptions<Input, Output> {
100
+ let handler: ToolCallback<Input, Output>;
99
101
  let inputStore: JsonEntityStore | undefined;
100
102
 
101
103
  if ("propertyKey" in options) {
@@ -140,9 +142,9 @@ function mapOptions<Input, Output = undefined>(options: ToolProps<Input, Output>
140
142
  * });
141
143
  * ```
142
144
  */
143
- export function defineTool<Input, Output = undefined>(options: FnToolProps<Input, Output>): TokenProvider;
144
- export function defineTool<Input, Output = undefined>(options: ClassToolProps<Input, Output>): TokenProvider;
145
- export function defineTool<Input, Output = undefined>(options: ToolProps<Input, Output>) {
145
+ export function defineTool<Input, Output = unknown>(options: FnToolProps<Input, Output>): TokenProvider;
146
+ export function defineTool<Input, Output = unknown>(options: ClassToolProps<Input, Output>): TokenProvider;
147
+ export function defineTool<Input, Output = unknown>(options: ToolProps<Input, Output>) {
146
148
  const provider = injectable(Symbol.for(`MCP:TOOL:${options.name}`))
147
149
  .type(MCP_PROVIDER_TYPES.TOOL)
148
150
  .factory(() => {
@@ -153,14 +155,26 @@ export function defineTool<Input, Output = undefined>(options: ToolProps<Input,
153
155
  ...opts,
154
156
  name: opts.name,
155
157
  inputSchema: toZod(inputSchema, {
158
+ groups: [opts.name!, "tools"],
159
+ useAlias: true
160
+ }),
161
+ outputSchema: toZod(opts.outputSchema, {
162
+ groups: [opts.name!, "tools"],
156
163
  useAlias: true
157
164
  }),
158
- outputSchema: toZod(opts.outputSchema),
159
165
  async handler(args: Input, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) {
160
166
  try {
161
- return await handler(deserializeInput(args, inputSchema, inputStore), extra);
167
+ const result = await handler(deserializeInput(args, inputSchema, inputStore), extra);
168
+
169
+ logger().info({
170
+ event: "MCP_TOOL_END",
171
+ tool: opts.name
172
+ });
173
+
174
+ return asToolResponse(result as unknown as Record<string, unknown>);
162
175
  } catch (er: any) {
163
176
  const code = er.name && er.status ? `E_MCP_TOOL_${constantCase(er.name)}` : "E_MCP_TOOL_ERROR";
177
+
164
178
  logger().error({
165
179
  event: "MCP_TOOL_ERROR",
166
180
  status_code: er.status,
@@ -171,16 +185,15 @@ export function defineTool<Input, Output = undefined>(options: ToolProps<Input,
171
185
  tool: opts.name
172
186
  });
173
187
 
174
- return {
175
- content: [],
176
- structuredContent: {
188
+ return asToolResponse(
189
+ {
177
190
  status_code: er.status,
178
191
  code,
179
192
  message: er.message,
180
- request_id: context().id,
181
193
  tool: opts.name
182
- }
183
- } satisfies CallToolResult;
194
+ },
195
+ {isError: true}
196
+ );
184
197
  }
185
198
  }
186
199
  };
package/src/index.ts CHANGED
@@ -11,4 +11,6 @@ export * from "./fn/defineTool.js";
11
11
  export * from "./interfaces/PlatformMcpSettings.js";
12
12
  export * from "./services/McpServerFactory.js";
13
13
  export * from "./services/PlatformMcpModule.js";
14
+ export * from "./utils/asResourceResponse.js";
15
+ export * from "./utils/asToolResponse.js";
14
16
  export * from "./utils/toZod.js";
@@ -0,0 +1,32 @@
1
+ import {asResourceResponse} from "./asResourceResponse.js";
2
+
3
+ describe("asResponse", () => {
4
+ it("should return a JSON content item for object payloads", () => {
5
+ expect(asResourceResponse("tsed://resource", {id: "resource-id"})).toEqual({
6
+ contents: [
7
+ {
8
+ uri: "tsed://resource",
9
+ mimeType: "application/json",
10
+ text: '{\n "id": "resource-id"\n}'
11
+ }
12
+ ]
13
+ });
14
+ });
15
+
16
+ it("should preserve an existing resource response", () => {
17
+ const response = {
18
+ contents: [{url: "tsed://resource", mimeType: "text/plain", text: "ready"}]
19
+ };
20
+
21
+ expect(asResourceResponse("tsed://ignored", response)).toBe(response);
22
+ });
23
+
24
+ it("should add a text error item before the JSON error payload", () => {
25
+ expect(asResourceResponse("tsed://resource", {message: "boom"}, {isError: true})).toEqual({
26
+ contents: [
27
+ {uri: "tsed://resource", mimeType: "plain/text", text: "boom"},
28
+ {uri: "tsed://resource", mimeType: "application/json", text: '{\n "message": "boom"\n}'}
29
+ ]
30
+ });
31
+ });
32
+ });