百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

tmcp

> 编程语言
开源

使用 TypeScript SDK 以无偏见的方式构建 MCP 服务器

196 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

使用 TypeScript SDK 以无偏见的方式构建 MCP 服务器

[!WARNING] Unfortunately i published the 1.0 by mistake...this package is currently under heavy development so there will be breaking changes in minors...threat this 1.x as the 0.x of any other package. Sorry for the disservice, every breaking will be properly labeled in the PR name.

tmcp

A lightweight, schema-agnostic Model Context Protocol (MCP) server implementation with unified API design.

Why tmcp?

tmcp offers significant advantages over the official MCP SDK:

  • ** Schema Agnostic**: Works with any validation library through adapters
  • ** No Weird Dependencies**: Minimal footprint with only essential dependencies (looking at you express)
  • ** Unified API**: Consistent, intuitive interface across all MCP capabilities
  • ** Extensible**: Easy to add support for new schema libraries
  • ⚡ Lightweight: No bloat, just what you need

Supported Schema Libraries

tmcp works with all major schema validation libraries through its adapter system:

  • Zod - @tmcp/adapter-zod
  • Valibot - @tmcp/adapter-valibot
  • ArkType - @tmcp/adapter-arktype
  • Effect Schema - @tmcp/adapter-effect
  • Zod v3 - @tmcp/adapter-zod-v3

Installation

bash
pnpm install tmcp
# Choose your preferred schema library adapter
pnpm install @tmcp/adapter-zod zod
# Choose your preferred transport
pnpm install @tmcp/transport-stdio  # For CLI/desktop apps
pnpm install @tmcp/transport-http   # For web-based clients

Quick Start

Standard I/O Transport (CLI/Desktop)

…

HTTP Transport (Web-based)

…

Defining Tools, Prompts, Resources, and Templates in Separate Files

For better code organization and reusability, you can define your tools, prompts, resources, and templates in separate files using the defineTool, definePrompt, defineResource, and defineTemplate utilities:

typescript
// tools/calculator.ts
import { defineTool } from 'tmcp/tool';
import { tool } from 'tmcp/utils';
import { z } from 'zod';

export const addTool = defineTool(
	{
		name: 'add',
		description: 'Add two numbers',
		schema: z.object({
			a: z.number(),
			b: z.number(),
		}),
	},
	async ({ a, b }) => tool.text(`${a} + ${b} = ${a + b}`),
);
typescript
// server.ts
import { McpServer } from 'tmcp';
import { addTool } from './tools/calculator.js';

const server = new McpServer(/* ... */);

// Register a single tool
server.tool(addTool);

// Or register multiple tools at once
server.tools([addTool, multiplyTool, divideTool]);

This approach enables:

  • Modular organization: Keep related functionality in separate files
  • Reusability: Share tool definitions across multiple servers
  • Better testing: Test tool logic independently
  • Type safety: Full TypeScript inference for parameters and return types

The same pattern works for definePrompt, defineResource, and defineTemplate with their corresponding server.prompts(), server.resources(), and server.templates() methods.

Adding the primitive to the server will error if the tool uses a different validation library than the one expressed in the adapter.

API Reference

McpServer

The main server class that handles MCP protocol communications.

Constructor

javascript
new McpServer(serverInfo, options);
  • serverInfo: Server metadata (name, version, description)
  • options: Configuration object with optional adapter (for schema conversion) and capabilities

[!IMPORTANT] While the adapter is optional (you can opt out by explicitly passing adapter: undefined) without an adapter the server cannot accept inputs, produce structured outputs, or request elicitations at all only do this for very simple servers.

Methods

tool(definition, handler) / tools(definitions)

Register one or more tools with optional schema validation.

…
prompt(definition, handler) / prompts(definitions)

Register one or more prompt templates with optional schema validation.

…
resource(definition, handler) / resources(definitions)

Register one or more static resources.

…

Reducing Return Boilerplate with tmcp/utils

Most handlers end by returning some variant of { content: [...] }, { messages: [...] }, or { completion: { ... } }. That shape is repetitive and easy to get wrong, especially when you also need to wire isError or structuredContent. The tmcp/utils entry point ships tiny factories that return the correct MCP payloads for you so handlers can stay focused on business logic.

…

you can also compose different kind of tools with tool.mix

typescript
tool.mix([
	tool.text('Indexed workspace'),
	tool.media('image', png, 'image/png'),
]);

however be aware that

  1. you can't pass tool.structured to tool.mix (but you can pass a second argument that will be the structured content)
  2. if you pass even one tool.error to the tool.mix the whole return value will be an error
typescript
const structuredContent = {
	cool: true,
};

tool.mix(
	[
		tool.text(JSON.stringify(structuredContent)),
		tool.media('image', png, 'image/png'),
	],
	structuredContent,
);

Each helper is fully typed and returns the correct MCP structure (CallToolResult, ReadResourceResult, GetPromptResult, or CompleteResult). That means you can still provide structuredContent, embed resources, or merge multiple results via mix without having to copy/paste the surrounding boilerplate.

template(definition, handler) / templates(definitions)

Register one or more URI templates for dynamic resources.

…
receive(request, context?)

Process an incoming MCP request with optional context information.

javascript
const response = server.receive(jsonRpcRequest, {
	sessionId: 'session-123',
	auth: authInfo,
	sessionInfo: {
		clientCapabilities, // cached from the client's initialize call
		clientInfo, // client name/version metadata
		logLevel, // last log level requested by the client
	},
	custom: {
		userId: 'alice',
	},
});

[!TIP] sessionInfo is automatically populated by the built-in transports. You can read it from handlers via server.ctx.sessionInfo to tailor behaviour to the connected client.

request({ method, params })

Send a raw JSON-RPC request to the connected client. This is useful for calling experimental MCP APIs or any custom client method that does not yet have a dedicated helper in McpServer or to send a request with a custom JSON-schema that is not expressible with your validation library.

javascript
const result = await server.request({
	method: 'elicitation/create',
	params: {
		message: 'Provide deployment metadata',
		requestedSchema: {
			type: 'object',
			required: ['region', 'replicas', 'features'],
			properties: {
				region: {
					type: 'string',
					enum: ['us-east-1', 'us-west-2', 'eu-central-1'],
				},
				replicas: { type: 'integer', minimum: 1, maximum: 20 },
				features: {
					type: 'array',
					items: {
						type: 'string',
						enum: ['canary', 'observability', 'autoscaling'],
					},
					minItems: 1,
				},
			},
		},
	},
});
  • method: Fully qualified MCP client method name
  • params (optional): JSON-RPC params object/array accepted by that method

Handle the resolved payload like any other JSON-RPC response—cast or (better) validate as needed when using this escape hatch.

Advanced Examples

Multiple Schema Libraries

javascript
// Use different schemas for different tools
import { z } from 'zod';
import * as v from 'valibot';

server.tool(
	{
		name: 'zod-tool',
		schema: z.object({ name: z.string() }),
	},
	async ({ name }) => `Hello ${name}`,
);

server.tool(
	{
		name: 'valibot-tool',
		schema: v.object({ age: v.number() }),
	},
	async ({ age }) => `Age: ${age}`,
);

Resource Templates with Completion

javascript
server.template(
	{
		name: 'user-profile',
		description: 'Get user profile by ID',
		uri: 'users/{userId}/profile',
		complete: (arg, context) => {
			// Provide completions for userId parameter
			return ['user1', 'user2', 'user3'];
		},
	},
	async (uri, params) => {
		const user = await getUserById(params.userId);
		return {
			contents: [
				{
					uri,
					mimeType: 'application/json',
					text: JSON.stringify(user),
				},
			],
		};
	},
);

Dynamic Properties with Getters

Sometimes you need properties that are computed dynamically at list-time rather than registration-time. For example, you might want to serve different descriptions based on which client is connected.

tmcp preserves JavaScript getters on the configuration object, allowing you to define properties that are evaluated each time the capability is listed:

javascript
server.tool(
	{
		name: 'search',
		get description() {
			const client = server.ctx.sessionInfo?.clientInfo?.name;
			if (client === 'claude-code') {
				return 'Search the codebase for files, symbols, or text patterns';
			}
			return 'Search for information';
		},
	},
	() => {
		return { content: [{ type: 'text', text: 'Search results...' }] };
	},
);

The same pattern works for resources, templates, and prompts.

Complex Validation

…

Contributing

Contributions are welcome! Please see our contributing guidelines for details.

Acknowledgments

Huge thanks to Sean O'Bannon that provided us with the @tmcp scope on npm.

License

MIT © Paolo Ricciuti

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

JavaScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言