@tsed/platform-mcp 8.31.2 → 8.32.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,10 +1,12 @@
1
+ import { JsonSchemaOptions } from "@tsed/schema";
1
2
  import { type ZodObject } from "zod";
2
3
  /**
3
4
  * Converts a {@link JsonSchema} produced by Ts.ED into an executable Zod validation object.
4
5
  *
5
6
  * @param schema JsonSchema instance or a pre-built Zod schema.
7
+ * @param opts
6
8
  * @returns A Zod object when conversion is possible, otherwise the original schema.
7
9
  * @module platform/mcp
8
10
  * @since 8.17.0
9
11
  */
10
- export declare function toZod(schema: unknown): ZodObject | undefined;
12
+ export declare function toZod(schema: unknown, opts?: JsonSchemaOptions): ZodObject | undefined;
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@tsed/platform-mcp",
3
3
  "description": "Model Context Protocol integration for Ts.ED HTTP adapters.",
4
4
  "type": "module",
5
- "version": "8.31.2",
5
+ "version": "8.32.0",
6
6
  "source": "./src/index.ts",
7
7
  "main": "./lib/esm/index.js",
8
8
  "module": "./lib/esm/index.js",
@@ -32,12 +32,13 @@
32
32
  "zod": ">=4.0.0"
33
33
  },
34
34
  "devDependencies": {
35
- "@tsed/barrels": "8.31.2",
36
- "@tsed/core": "8.31.2",
37
- "@tsed/di": "8.31.2",
38
- "@tsed/platform-http": "8.31.2",
39
- "@tsed/schema": "8.31.2",
40
- "@tsed/typescript": "8.31.2",
35
+ "@tsed/barrels": "8.32.0",
36
+ "@tsed/core": "8.32.0",
37
+ "@tsed/di": "8.32.0",
38
+ "@tsed/json-mapper": "8.32.0",
39
+ "@tsed/platform-http": "8.32.0",
40
+ "@tsed/schema": "8.32.0",
41
+ "@tsed/typescript": "8.32.0",
41
42
  "eslint": "9.12.0",
42
43
  "typescript": "6.0.2",
43
44
  "vitest": "4.1.4"
@@ -45,6 +46,7 @@
45
46
  "peerDependencies": {
46
47
  "@tsed/core": ">=8.0.0",
47
48
  "@tsed/di": ">=8.0.0",
49
+ "@tsed/json-mapper": ">=8.0.0",
48
50
  "@tsed/platform-http": ">=8.0.0",
49
51
  "@tsed/schema": ">=8.0.0"
50
52
  },
@@ -55,6 +57,9 @@
55
57
  "@tsed/di": {
56
58
  "optional": false
57
59
  },
60
+ "@tsed/json-mapper": {
61
+ "optional": false
62
+ },
58
63
  "@tsed/platform-http": {
59
64
  "optional": false
60
65
  },
@@ -1,5 +1,5 @@
1
1
  import {DITest, inject, Injectable} from "@tsed/di";
2
- import {CollectionOf, Description, Property, Returns} from "@tsed/schema";
2
+ import {CollectionOf, Default, Description, Name, Property, Returns} from "@tsed/schema";
3
3
 
4
4
  import {Tool} from "./tool.js";
5
5
 
@@ -8,6 +8,17 @@ class Model {
8
8
  public name: string;
9
9
  }
10
10
 
11
+ class AliasedModel {
12
+ @Default(10)
13
+ @Name("top_k")
14
+ @Property()
15
+ topK: number = 10;
16
+
17
+ @Name("request_id")
18
+ @Property()
19
+ requestId?: string;
20
+ }
21
+
11
22
  class Item {
12
23
  @Property()
13
24
  public name: string;
@@ -20,6 +31,8 @@ class Output {
20
31
 
21
32
  @Injectable()
22
33
  class TestTool {
34
+ public input?: AliasedModel;
35
+
23
36
  @Tool("test-tool")
24
37
  @Description("Test description")
25
38
  @Returns(200, Output)
@@ -33,6 +46,15 @@ class TestTool {
33
46
  tool2(input: Model) {
34
47
  return new Output();
35
48
  }
49
+
50
+ @Tool("deserialized-tool")
51
+ @Description("Test description")
52
+ @Returns(200, Output)
53
+ tool3(input: AliasedModel) {
54
+ this.input = input;
55
+
56
+ return new Output();
57
+ }
36
58
  }
37
59
 
38
60
  describe("Tool", () => {
@@ -65,4 +87,23 @@ describe("Tool", () => {
65
87
  outputSchema: expect.any(Object)
66
88
  });
67
89
  });
90
+
91
+ it("should deserialize tool input from decorator metadata", async () => {
92
+ const tool = inject<any>(Symbol.for(`MCP:TOOL:deserialized-tool`));
93
+ const service = inject(TestTool);
94
+
95
+ await tool.handler(
96
+ {
97
+ top_k: 12,
98
+ request_id: "req-123"
99
+ },
100
+ {} as any
101
+ );
102
+
103
+ expect(service.input).toBeInstanceOf(AliasedModel);
104
+ expect(service.input).toMatchObject({
105
+ topK: 12,
106
+ requestId: "req-123"
107
+ });
108
+ });
68
109
  });
@@ -1,9 +1,28 @@
1
1
  import {inject} from "@tsed/di";
2
2
  import {PlatformTest} from "@tsed/platform-http/testing";
3
+ import {Default, from, JsonSchema, Name, Property} from "@tsed/schema";
3
4
  import {afterEach, beforeEach, describe, expect, it} from "vitest";
4
5
 
5
6
  import {defineTool} from "./defineTool.js";
6
7
 
8
+ class KnowledgeSearchRequest {
9
+ @Property()
10
+ query!: string;
11
+
12
+ @Default(10)
13
+ @Name("top_k")
14
+ @Property()
15
+ topK: number = 10;
16
+
17
+ @Name("request_id")
18
+ @Property()
19
+ requestId?: string;
20
+
21
+ constructor(props: Partial<KnowledgeSearchRequest> = {}) {
22
+ Object.assign(this, props);
23
+ }
24
+ }
25
+
7
26
  describe("defineTool", () => {
8
27
  beforeEach(() => PlatformTest.create());
9
28
  afterEach(() => PlatformTest.reset());
@@ -52,4 +71,62 @@ describe("defineTool", () => {
52
71
  tool: "http-tool"
53
72
  });
54
73
  });
74
+
75
+ it("should expose aliased input schema properties", () => {
76
+ const token = defineTool<any>({
77
+ name: "aliased-tool",
78
+ inputSchema: JsonSchema.from({
79
+ type: "object",
80
+ properties: {
81
+ prop: {
82
+ type: "string"
83
+ }
84
+ },
85
+ required: ["prop"]
86
+ }).addAlias("prop", "aliasProp"),
87
+ handler() {
88
+ return {content: []};
89
+ }
90
+ });
91
+
92
+ const definition = inject<any>(token);
93
+
94
+ expect(definition.inputSchema.toJSONSchema()).toEqual({
95
+ $schema: "https://json-schema.org/draft/2020-12/schema",
96
+ type: "object",
97
+ properties: {
98
+ aliasProp: {
99
+ type: "string"
100
+ }
101
+ },
102
+ required: ["aliasProp"],
103
+ additionalProperties: false
104
+ });
105
+ });
106
+
107
+ it("should deserialize functional tool input from a Ts.ED model schema", async () => {
108
+ const token = defineTool<KnowledgeSearchRequest>({
109
+ name: "knowledge-search",
110
+ inputSchema: from(KnowledgeSearchRequest).omit("query"),
111
+ handler(input) {
112
+ expect(input).toBeInstanceOf(KnowledgeSearchRequest);
113
+ expect(input.topK).toBe(12);
114
+ expect(input.requestId).toBe("req-123");
115
+
116
+ return {
117
+ content: []
118
+ };
119
+ }
120
+ });
121
+
122
+ const definition = inject<any>(token);
123
+
124
+ await definition.handler(
125
+ {
126
+ top_k: 12,
127
+ request_id: "req-123"
128
+ },
129
+ {} as any
130
+ );
131
+ });
55
132
  });
@@ -1,7 +1,8 @@
1
1
  import type {RequestHandlerExtra} from "@modelcontextprotocol/sdk/shared/protocol.js";
2
2
  import type {CallToolResult, ServerNotification, ServerRequest, Tool, ToolAnnotations} from "@modelcontextprotocol/sdk/types.js";
3
- import {type AbstractType, isArrowFn, type Type} from "@tsed/core";
3
+ import {type AbstractType, isArrowFn, isClass, type Type} from "@tsed/core";
4
4
  import {context, inject, injectable, logger, type TokenProvider} from "@tsed/di";
5
+ import {deserialize} from "@tsed/json-mapper";
5
6
  import {JsonEntityStore, JsonMethodStore, JsonSchema} from "@tsed/schema";
6
7
  import {constantCase} from "change-case";
7
8
 
@@ -57,6 +58,11 @@ export type ClassToolProps<Input, Output = undefined> = BaseToolProps<Input, Out
57
58
  */
58
59
  export type ToolProps<Input, Output = undefined> = FnToolProps<Input, Output> | ClassToolProps<Input, Output>;
59
60
 
61
+ type MappedToolOptions<Input, Output = undefined> = Omit<ToolProps<Input, Output>, "token" | "propertyKey"> & {
62
+ handler: ToolCallback<Input>;
63
+ inputStore?: JsonEntityStore;
64
+ };
65
+
60
66
  function getOutputSchema<Output>(methodStore: JsonMethodStore): JsonSchema<Output> {
61
67
  const schema: JsonSchema = methodStore.operation.getResponseOf(200)?.getMedia("application/json")?.get("schema");
62
68
 
@@ -67,11 +73,35 @@ function getInputSchema<Input>(token: Type<any> | AbstractType<any>, propertyKey
67
73
  return JsonEntityStore.from(token, propertyKey, 0).schema?.itemSchema() as JsonSchema<Input>;
68
74
  }
69
75
 
70
- function mapOptions<Input, Output = undefined>(options: ToolProps<Input, Output>) {
76
+ function resolveInputSchema<Input>(inputSchema: JsonSchema<Input> | (() => JsonSchema<Input>) | Tool["inputSchema"] | undefined) {
77
+ return isArrowFn(inputSchema) ? inputSchema() : inputSchema;
78
+ }
79
+
80
+ function deserializeInput<Input>(args: Input, inputSchema: unknown, inputStore?: JsonEntityStore): Input {
81
+ if (!(inputSchema instanceof JsonSchema)) {
82
+ return args;
83
+ }
84
+
85
+ const type = inputStore?.getBestType?.() || inputSchema.getTarget();
86
+
87
+ if (!type || type === Object || !isClass(type)) {
88
+ return args;
89
+ }
90
+
91
+ return deserialize(args, {
92
+ type,
93
+ store: inputStore,
94
+ useAlias: true
95
+ }) as Input;
96
+ }
97
+
98
+ function mapOptions<Input, Output = undefined>(options: ToolProps<Input, Output>): MappedToolOptions<Input, Output> {
71
99
  let handler: ToolCallback<Input>;
100
+ let inputStore: JsonEntityStore | undefined;
72
101
 
73
102
  if ("propertyKey" in options) {
74
103
  const {token, propertyKey} = options;
104
+ inputStore = JsonEntityStore.from(token, propertyKey, 0);
75
105
  handler = (args: Input, extra: any) => {
76
106
  const instance = inject(options.token) as any;
77
107
  return instance[options.propertyKey](args, extra);
@@ -79,7 +109,8 @@ function mapOptions<Input, Output = undefined>(options: ToolProps<Input, Output>
79
109
 
80
110
  const methodStore = JsonEntityStore.fromMethod(token, propertyKey);
81
111
  options.description = options.description || methodStore.operation.get("description");
82
- options.inputSchema = options.inputSchema || getInputSchema(token, propertyKey);
112
+ options.inputSchema =
113
+ options.inputSchema || ((inputStore.schema?.itemSchema() || getInputSchema(token, propertyKey)) as JsonSchema<Input>);
83
114
  options.outputSchema = options.outputSchema || getOutputSchema(methodStore);
84
115
  } else {
85
116
  handler = options.handler;
@@ -87,7 +118,8 @@ function mapOptions<Input, Output = undefined>(options: ToolProps<Input, Output>
87
118
 
88
119
  return {
89
120
  ...options,
90
- handler
121
+ handler,
122
+ inputStore
91
123
  };
92
124
  }
93
125
 
@@ -115,16 +147,19 @@ export function defineTool<Input, Output = undefined>(options: ToolProps<Input,
115
147
  const provider = injectable(Symbol.for(`MCP:TOOL:${options.name}`))
116
148
  .type(MCP_PROVIDER_TYPES.TOOL)
117
149
  .factory(() => {
118
- let {handler, ...opts} = mapOptions(options);
150
+ const {handler, inputStore, ...opts} = mapOptions(options);
151
+ const inputSchema = resolveInputSchema(opts.inputSchema);
119
152
 
120
153
  return {
121
154
  ...opts,
122
155
  name: opts.name,
123
- inputSchema: toZod(isArrowFn(opts.inputSchema) ? opts.inputSchema() : opts.inputSchema),
156
+ inputSchema: toZod(inputSchema, {
157
+ useAlias: true
158
+ }),
124
159
  outputSchema: toZod(opts.outputSchema),
125
160
  async handler(args: Input, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) {
126
161
  try {
127
- return await handler(args as Input, extra);
162
+ return await handler(deserializeInput(args, inputSchema, inputStore), extra);
128
163
  } catch (er: any) {
129
164
  const code = er.name && er.status ? `E_MCP_TOOL_${constantCase(er.name)}` : "E_MCP_TOOL_ERROR";
130
165
  logger().error({
@@ -1,4 +1,4 @@
1
- import {s, string} from "@tsed/schema";
1
+ import {JsonSchema, s, string} from "@tsed/schema";
2
2
 
3
3
  import {toZod} from "./toZod.js";
4
4
 
@@ -12,4 +12,30 @@ describe("toZod", () => {
12
12
 
13
13
  expect(result?.toJSONSchema).toBeDefined();
14
14
  });
15
+
16
+ it("should preserve aliases when useAlias is enabled", () => {
17
+ const schema = JsonSchema.from({
18
+ type: "object",
19
+ properties: {
20
+ prop: {
21
+ type: "string"
22
+ }
23
+ },
24
+ required: ["prop"]
25
+ }).addAlias("prop", "aliasProp");
26
+
27
+ const result = toZod(schema, {useAlias: true});
28
+
29
+ expect(result?.toJSONSchema()).toEqual({
30
+ $schema: "https://json-schema.org/draft/2020-12/schema",
31
+ type: "object",
32
+ properties: {
33
+ aliasProp: {
34
+ type: "string"
35
+ }
36
+ },
37
+ required: ["aliasProp"],
38
+ additionalProperties: false
39
+ });
40
+ });
15
41
  });
@@ -1,9 +1,9 @@
1
- import {JsonSchema} from "@tsed/schema";
1
+ import {JsonSchema, JsonSchemaOptions} from "@tsed/schema";
2
2
  import {jsonSchemaToZod} from "json-schema-to-zod";
3
3
  import {z, type ZodObject} from "zod";
4
4
 
5
- function transform(schema: JsonSchema): ZodObject {
6
- const schemaFactory = new Function("z", `return ${jsonSchemaToZod(schema.toJSON(), {zodVersion: 4})}`) as (zod: unknown) => ZodObject;
5
+ function transform(schema: JsonSchema, opts?: JsonSchemaOptions): ZodObject {
6
+ const schemaFactory = new Function("z", `return ${jsonSchemaToZod(schema.toJSON(opts), {zodVersion: 4})}`) as (zod: unknown) => ZodObject;
7
7
 
8
8
  return schemaFactory(z);
9
9
  }
@@ -12,10 +12,11 @@ function transform(schema: JsonSchema): ZodObject {
12
12
  * Converts a {@link JsonSchema} produced by Ts.ED into an executable Zod validation object.
13
13
  *
14
14
  * @param schema JsonSchema instance or a pre-built Zod schema.
15
+ * @param opts
15
16
  * @returns A Zod object when conversion is possible, otherwise the original schema.
16
17
  * @module platform/mcp
17
18
  * @since 8.17.0
18
19
  */
19
- export function toZod(schema: unknown): ZodObject | undefined {
20
- return schema && schema instanceof JsonSchema ? transform(schema) : (schema as ZodObject | undefined);
20
+ export function toZod(schema: unknown, opts?: JsonSchemaOptions): ZodObject | undefined {
21
+ return schema && schema instanceof JsonSchema ? transform(schema, opts) : (schema as ZodObject | undefined);
21
22
  }