trpc-to-mcp 1.0.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.
@@ -0,0 +1,8 @@
1
+ # Changesets
2
+
3
+ Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
4
+ with multi-package repos, or single-package repos to help you version and publish your code. You can
5
+ find the full documentation for it [in our repository](https://github.com/changesets/changesets)
6
+
7
+ We have a quick list of common questions to get you started engaging with this project in
8
+ [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
@@ -0,0 +1,11 @@
1
+ {
2
+ "$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json",
3
+ "changelog": "@changesets/cli/changelog",
4
+ "commit": false,
5
+ "fixed": [],
6
+ "linked": [],
7
+ "access": "public",
8
+ "baseBranch": "main",
9
+ "updateInternalDependencies": "patch",
10
+ "ignore": []
11
+ }
@@ -0,0 +1,21 @@
1
+ name: CI
2
+ on:
3
+ push:
4
+ branches:
5
+ - "**"
6
+
7
+ jobs:
8
+ build:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v3
12
+ - uses: pnpm/action-setup@v2
13
+ with:
14
+ version: 9
15
+ - uses: actions/setup-node@v3
16
+ with:
17
+ node-version: 20.x
18
+ cache: "pnpm"
19
+
20
+ - run: pnpm install --frozen-lockfile
21
+ - run: pnpm run lint && pnpm run build
@@ -0,0 +1,36 @@
1
+ name: Publish
2
+ on:
3
+ workflow_run:
4
+ workflows: [CI]
5
+ branches: [main]
6
+ types: [completed]
7
+
8
+ concurrency: ${{ github.workflow }}-${{ github.ref }}
9
+
10
+ permissions:
11
+ contents: write
12
+ pull-requests: write
13
+
14
+ jobs:
15
+ publish:
16
+ if: ${{ github.event.workflow_run.conclusion == 'success' }}
17
+ runs-on: ubuntu-latest
18
+ steps:
19
+ - uses: actions/checkout@v3
20
+ - uses: pnpm/action-setup@v2
21
+ with:
22
+ version: 9
23
+ - uses: actions/setup-node@v3
24
+ with:
25
+ node-version: 20.x
26
+ cache: "pnpm"
27
+
28
+ - run: pnpm install --frozen-lockfile
29
+ - name: Create Release Pull Request or Publish
30
+ id: changesets
31
+ uses: changesets/action@v1
32
+ with:
33
+ publish: pnpm run release --access public
34
+ env:
35
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
36
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # trpc-to-mcp
2
+
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 7341e0f: Release package
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 iboughtbed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,17 @@
1
+ import { Implementation } from '@modelcontextprotocol/sdk/types.js';
2
+ import { AnyRootTypes, RouterRecord, Router } from '@trpc/server/unstable-core-do-not-import';
3
+ import { z } from 'zod/v4';
4
+
5
+ type MaybePromise<T> = Promise<T> | T;
6
+ declare function createMcpServer<TRoot extends AnyRootTypes, TRecord extends RouterRecord>(implementation: Implementation, appRouter: Router<TRoot, TRecord>, ctx: TRoot["ctx"] | (() => MaybePromise<TRoot["ctx"]>)): void;
7
+
8
+ type McpTool = {
9
+ name: string;
10
+ description: string;
11
+ pathInRouter: string[];
12
+ inputSchema?: z.core.JSONSchema.JSONSchema;
13
+ };
14
+ declare function mergeInputs(inputs: z.ZodObject[]): z.ZodObject<z.core.$ZodLooseShape, z.core.$strip>;
15
+ declare function extractToolsFromProcedures<TRoot extends AnyRootTypes, TRecord extends RouterRecord>(appRouter: Router<TRoot, TRecord>, currentPath?: string[]): McpTool[];
16
+
17
+ export { type McpTool, createMcpServer, extractToolsFromProcedures, mergeInputs };
@@ -0,0 +1,17 @@
1
+ import { Implementation } from '@modelcontextprotocol/sdk/types.js';
2
+ import { AnyRootTypes, RouterRecord, Router } from '@trpc/server/unstable-core-do-not-import';
3
+ import { z } from 'zod/v4';
4
+
5
+ type MaybePromise<T> = Promise<T> | T;
6
+ declare function createMcpServer<TRoot extends AnyRootTypes, TRecord extends RouterRecord>(implementation: Implementation, appRouter: Router<TRoot, TRecord>, ctx: TRoot["ctx"] | (() => MaybePromise<TRoot["ctx"]>)): void;
7
+
8
+ type McpTool = {
9
+ name: string;
10
+ description: string;
11
+ pathInRouter: string[];
12
+ inputSchema?: z.core.JSONSchema.JSONSchema;
13
+ };
14
+ declare function mergeInputs(inputs: z.ZodObject[]): z.ZodObject<z.core.$ZodLooseShape, z.core.$strip>;
15
+ declare function extractToolsFromProcedures<TRoot extends AnyRootTypes, TRecord extends RouterRecord>(appRouter: Router<TRoot, TRecord>, currentPath?: string[]): McpTool[];
16
+
17
+ export { type McpTool, createMcpServer, extractToolsFromProcedures, mergeInputs };
package/dist/index.js ADDED
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createMcpServer: () => createMcpServer,
24
+ extractToolsFromProcedures: () => extractToolsFromProcedures,
25
+ mergeInputs: () => mergeInputs
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/server.ts
30
+ var import_server = require("@modelcontextprotocol/sdk/server/index.js");
31
+ var import_types = require("@modelcontextprotocol/sdk/types.js");
32
+
33
+ // src/tools.ts
34
+ var import_v4 = require("zod/v4");
35
+ function mergeInputs(inputs) {
36
+ return inputs.reduce((acc, input) => {
37
+ return acc.extend(input.shape);
38
+ }, import_v4.z.object());
39
+ }
40
+ function extractToolsFromProcedures(appRouter, currentPath = []) {
41
+ const tools = [];
42
+ const procedures = Object.entries(appRouter._def.procedures);
43
+ for (const [name, procedure] of procedures) {
44
+ if (procedure._def && "inputs" in procedure._def) {
45
+ const inputs = procedure._def.inputs;
46
+ const schema = inputs.length > 1 ? mergeInputs(inputs) : inputs[0];
47
+ const meta = procedure._def.meta;
48
+ if (!meta || !meta?.mcp?.enabled) {
49
+ continue;
50
+ }
51
+ const pathInRouter = [...currentPath, ...name.split(".")];
52
+ const tool = {
53
+ name: meta?.mcp?.name ?? name.replace(/\./g, "_"),
54
+ description: meta?.mcp?.description ?? "",
55
+ pathInRouter
56
+ };
57
+ if (schema) {
58
+ const jsonSchema = import_v4.z.toJSONSchema(schema, {
59
+ unrepresentable: "any"
60
+ });
61
+ if (jsonSchema.type === "object") {
62
+ const { type, properties = {}, required = [] } = jsonSchema;
63
+ tool.inputSchema = { type, properties, required };
64
+ } else {
65
+ console.error(
66
+ "[TRPC-TO-MCP] Procedure has no object schema",
67
+ pathInRouter
68
+ );
69
+ }
70
+ } else {
71
+ const jsonSchema = import_v4.z.toJSONSchema(import_v4.z.object());
72
+ tool.inputSchema = jsonSchema;
73
+ }
74
+ tools.push(tool);
75
+ }
76
+ }
77
+ return tools;
78
+ }
79
+
80
+ // src/server.ts
81
+ function createMcpServer(implementation, appRouter, ctx) {
82
+ const tools = extractToolsFromProcedures(appRouter);
83
+ const trpcCaller = appRouter.createCaller(ctx);
84
+ const server = new import_server.Server(implementation, {
85
+ capabilities: {
86
+ // Leave it empty because we list tools manually
87
+ tools: {}
88
+ }
89
+ });
90
+ server.setRequestHandler(import_types.ListToolsRequestSchema, () => ({ tools }));
91
+ server.setRequestHandler(import_types.CallToolRequestSchema, async (request) => {
92
+ const { name, arguments: args } = request.params;
93
+ const tool = tools.find((t) => t.name === name);
94
+ if (!tool) {
95
+ return { content: [{ type: "text", text: "Could not find tool" }] };
96
+ }
97
+ const procedure = tool.pathInRouter.reduce(
98
+ // @ts-expect-error path in router
99
+ (acc, part) => acc?.[part],
100
+ trpcCaller
101
+ );
102
+ const result = await procedure(args);
103
+ return {
104
+ content: [{ type: "text", text: JSON.stringify(result) }]
105
+ };
106
+ });
107
+ }
108
+ // Annotate the CommonJS export names for ESM import in node:
109
+ 0 && (module.exports = {
110
+ createMcpServer,
111
+ extractToolsFromProcedures,
112
+ mergeInputs
113
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,87 @@
1
+ // src/server.ts
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import {
4
+ CallToolRequestSchema,
5
+ ListToolsRequestSchema
6
+ } from "@modelcontextprotocol/sdk/types.js";
7
+
8
+ // src/tools.ts
9
+ import { z } from "zod/v4";
10
+ function mergeInputs(inputs) {
11
+ return inputs.reduce((acc, input) => {
12
+ return acc.extend(input.shape);
13
+ }, z.object());
14
+ }
15
+ function extractToolsFromProcedures(appRouter, currentPath = []) {
16
+ const tools = [];
17
+ const procedures = Object.entries(appRouter._def.procedures);
18
+ for (const [name, procedure] of procedures) {
19
+ if (procedure._def && "inputs" in procedure._def) {
20
+ const inputs = procedure._def.inputs;
21
+ const schema = inputs.length > 1 ? mergeInputs(inputs) : inputs[0];
22
+ const meta = procedure._def.meta;
23
+ if (!meta || !meta?.mcp?.enabled) {
24
+ continue;
25
+ }
26
+ const pathInRouter = [...currentPath, ...name.split(".")];
27
+ const tool = {
28
+ name: meta?.mcp?.name ?? name.replace(/\./g, "_"),
29
+ description: meta?.mcp?.description ?? "",
30
+ pathInRouter
31
+ };
32
+ if (schema) {
33
+ const jsonSchema = z.toJSONSchema(schema, {
34
+ unrepresentable: "any"
35
+ });
36
+ if (jsonSchema.type === "object") {
37
+ const { type, properties = {}, required = [] } = jsonSchema;
38
+ tool.inputSchema = { type, properties, required };
39
+ } else {
40
+ console.error(
41
+ "[TRPC-TO-MCP] Procedure has no object schema",
42
+ pathInRouter
43
+ );
44
+ }
45
+ } else {
46
+ const jsonSchema = z.toJSONSchema(z.object());
47
+ tool.inputSchema = jsonSchema;
48
+ }
49
+ tools.push(tool);
50
+ }
51
+ }
52
+ return tools;
53
+ }
54
+
55
+ // src/server.ts
56
+ function createMcpServer(implementation, appRouter, ctx) {
57
+ const tools = extractToolsFromProcedures(appRouter);
58
+ const trpcCaller = appRouter.createCaller(ctx);
59
+ const server = new Server(implementation, {
60
+ capabilities: {
61
+ // Leave it empty because we list tools manually
62
+ tools: {}
63
+ }
64
+ });
65
+ server.setRequestHandler(ListToolsRequestSchema, () => ({ tools }));
66
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
67
+ const { name, arguments: args } = request.params;
68
+ const tool = tools.find((t) => t.name === name);
69
+ if (!tool) {
70
+ return { content: [{ type: "text", text: "Could not find tool" }] };
71
+ }
72
+ const procedure = tool.pathInRouter.reduce(
73
+ // @ts-expect-error path in router
74
+ (acc, part) => acc?.[part],
75
+ trpcCaller
76
+ );
77
+ const result = await procedure(args);
78
+ return {
79
+ content: [{ type: "text", text: JSON.stringify(result) }]
80
+ };
81
+ });
82
+ }
83
+ export {
84
+ createMcpServer,
85
+ extractToolsFromProcedures,
86
+ mergeInputs
87
+ };
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "trpc-to-mcp",
3
+ "license": "MIT",
4
+ "version": "1.0.0",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "devDependencies": {
9
+ "@changesets/cli": "^2.29.5",
10
+ "tsup": "^8.5.0",
11
+ "typescript": "^5.9.2"
12
+ },
13
+ "peerDependencies": {
14
+ "@trpc/server": "^11.4.4",
15
+ "zod": "^4.0.15"
16
+ },
17
+ "dependencies": {
18
+ "@modelcontextprotocol/sdk": "^1.17.2"
19
+ },
20
+ "scripts": {
21
+ "build": "tsup ./src/index.ts --format cjs,esm --dts",
22
+ "release": "pnpm run build && changeset publish",
23
+ "lint": "tsc"
24
+ }
25
+ }
File without changes
File without changes
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./server";
2
+ export * from "./tools";
package/src/server.ts ADDED
@@ -0,0 +1,63 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import {
3
+ CallToolRequestSchema,
4
+ type Implementation,
5
+ ListToolsRequestSchema,
6
+ } from "@modelcontextprotocol/sdk/types.js";
7
+ import type {
8
+ AnyProcedure,
9
+ AnyRootTypes,
10
+ Router,
11
+ RouterRecord,
12
+ } from "@trpc/server/unstable-core-do-not-import";
13
+
14
+ import { extractToolsFromProcedures } from "./tools";
15
+
16
+ type MaybePromise<T> = Promise<T> | T;
17
+
18
+ export function createMcpServer<
19
+ TRoot extends AnyRootTypes,
20
+ TRecord extends RouterRecord
21
+ >(
22
+ implementation: Implementation,
23
+ appRouter: Router<TRoot, TRecord>,
24
+ ctx: TRoot["ctx"] | (() => MaybePromise<TRoot["ctx"]>)
25
+ ) {
26
+ const tools = extractToolsFromProcedures(appRouter);
27
+ const trpcCaller = appRouter.createCaller(ctx);
28
+
29
+ const server = new Server(implementation, {
30
+ capabilities: {
31
+ // Leave it empty because we list tools manually
32
+ tools: {},
33
+ },
34
+ });
35
+
36
+ // List all of the available tools
37
+ server.setRequestHandler(ListToolsRequestSchema, () => ({ tools }));
38
+
39
+ // Handle tool calls
40
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
41
+ const { name, arguments: args } = request.params;
42
+
43
+ const tool = tools.find((t) => t.name === name);
44
+
45
+ if (!tool) {
46
+ return { content: [{ type: "text", text: "Could not find tool" }] };
47
+ }
48
+
49
+ // @ts-expect-error path in router
50
+ const procedure: AnyProcedure = tool.pathInRouter.reduce(
51
+ // @ts-expect-error path in router
52
+ (acc, part) => acc?.[part],
53
+ trpcCaller
54
+ );
55
+
56
+ // @ts-expect-error path in router
57
+ const result = await procedure(args);
58
+
59
+ return {
60
+ content: [{ type: "text", text: JSON.stringify(result) }],
61
+ };
62
+ });
63
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,74 @@
1
+ // Credits to https://github.com/Jacse/trpc-mcp for the helpful code
2
+
3
+ import type {
4
+ AnyRootTypes,
5
+ Router,
6
+ RouterRecord,
7
+ } from "@trpc/server/unstable-core-do-not-import";
8
+ import { z } from "zod/v4";
9
+
10
+ import type { McpMeta } from "./types";
11
+
12
+ export type McpTool = {
13
+ name: string;
14
+ description: string;
15
+ pathInRouter: string[];
16
+ inputSchema?: z.core.JSONSchema.JSONSchema;
17
+ };
18
+
19
+ export function mergeInputs(inputs: z.ZodObject[]) {
20
+ return inputs.reduce((acc, input) => {
21
+ return acc.extend(input.shape);
22
+ }, z.object());
23
+ }
24
+
25
+ export function extractToolsFromProcedures<
26
+ TRoot extends AnyRootTypes,
27
+ TRecord extends RouterRecord
28
+ >(appRouter: Router<TRoot, TRecord>, currentPath: string[] = []) {
29
+ const tools: McpTool[] = [];
30
+ const procedures = Object.entries(appRouter._def.procedures);
31
+
32
+ for (const [name, procedure] of procedures) {
33
+ if (procedure._def && "inputs" in procedure._def) {
34
+ const inputs = procedure._def.inputs as z.ZodObject[];
35
+ const schema = inputs.length > 1 ? mergeInputs(inputs) : inputs[0];
36
+
37
+ const meta = procedure._def.meta as McpMeta;
38
+ if (!meta || !meta?.mcp?.enabled) {
39
+ continue;
40
+ }
41
+
42
+ const pathInRouter = [...currentPath, ...name.split(".")];
43
+ const tool: McpTool = {
44
+ name: meta?.mcp?.name ?? name.replace(/\./g, "_"),
45
+ description: meta?.mcp?.description ?? "",
46
+ pathInRouter,
47
+ };
48
+
49
+ if (schema) {
50
+ const jsonSchema = z.toJSONSchema(schema, {
51
+ unrepresentable: "any",
52
+ });
53
+
54
+ if (jsonSchema.type === "object") {
55
+ const { type, properties = {}, required = [] } = jsonSchema;
56
+ tool.inputSchema = { type, properties, required };
57
+ } else {
58
+ console.error(
59
+ "[TRPC-TO-MCP] Procedure has no object schema",
60
+ pathInRouter
61
+ );
62
+ }
63
+ } else {
64
+ // If there is not schema, we have to pass an empty object for JSON schema compatibility
65
+ const jsonSchema = z.toJSONSchema(z.object());
66
+ tool.inputSchema = jsonSchema;
67
+ }
68
+
69
+ tools.push(tool);
70
+ }
71
+ }
72
+
73
+ return tools;
74
+ }
package/src/types.ts ADDED
@@ -0,0 +1,7 @@
1
+ export type McpMeta = {
2
+ mcp?: {
3
+ enabled?: boolean;
4
+ description?: string;
5
+ name?: string;
6
+ };
7
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "commonjs",
5
+ "esModuleInterop": true,
6
+ "forceConsistentCasingInFileNames": true,
7
+ "strict": true,
8
+ "skipLibCheck": true,
9
+ "noUncheckedIndexedAccess": true,
10
+ "noEmit": true
11
+ }
12
+ }