Practical TypeScript MCP Server: Securely Integrating Team Business Tools with Cursor
93% Completion: Delivering Zod Contract Validation and Stable stdio Communication for Seamless IDE Capability Extension.

Completion Score
Overall completion is 93%. AI performance was exceptional in generating Zod Schemas and MCP protocol encapsulation code, significantly reducing boilerplate. Manual review must focus on environment variable injection logic and permission boundaries to ensure production environment security.
Dimension breakdown
Zod offers excellent type derivation and runtime validation. The description field maps directly to AI prompts with extremely high accuracy.
Enforcing read-only mode via environment variables and double-checking at the code level effectively prevents AI from accidentally triggering write operations.
The stdio transport layer is stable, but it is crucial to strictly distinguish stdout (protocol data) from stderr (logs) to avoid polluting the JSON-RPC stream.
Structured error objects aid AI self-correction, but ensure error messages do not contain sensitive stack trace information to prevent data leaks.
Human checkpoint
Manual review of environment variable references in .cursor/mcp.json is mandatory to ensure API_KEY is not hardcoded and that READ_ONLY_MODE functions correctly in the test environment.
Upgrade / downgrade path
If resources are constrained, complex logging middleware can be removed, retaining only core stdio communication. If expansion is needed, a Redis caching layer can be introduced to accelerate high-frequency query responses.
When to use & prerequisites
Suitable for teams with a TypeScript tech stack; the environment must have Node.js 18+ and the Cursor IDE pre-installed. Ideal use cases include internal data queries and document retrieval in read-only scenarios, avoiding direct AI operations on production databases.
Ready-to-copy configs
定义 MCP 服务器启动命令、环境变量及只读/写权限隔离策略。
{
"mcpServers": {
"team-business-tools": {
"command": "node",
"args": ["dist/mcp-server.js"],
"env": {
"NODE_ENV": "production",
"API_BASE_URL": "${API_BASE_URL}",
"API_KEY": "${API_KEY}",
"READ_ONLY_MODE": "true"
},
"disabled": false,
"autoApprove": false
}
}
}基于 MCP SDK 与 Zod 实现的 stdio 服务器,包含参数校验与结构化错误处理。
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new Server({ name: "team-business-tools", version: "1.0.0" }, { capabilities: { tools: {} } });
const querySchema = z.object({
query: z.string().min(1).describe("业务查询语句"),
limit: z.number().int().min(1).max(100).default(10).describe("返回条数限制")
});
server.setRequestHandler("tools/list", async () => ({
tools: [{
name: "query_business_data",
description: "安全查询团队业务数据(只读)",
inputSchema: querySchema.shape
}]
}));
server.setRequestHandler("tools/call", async (request) => {
try {
if (request.params.name !== "query_business_data") throw new Error("Unknown tool");
const parsed = querySchema.parse(request.params.arguments);
// Simulate API call with READ_ONLY_MODE guard
if (process.env.READ_ONLY_MODE !== "true") throw new Error("Write operations disabled in safe mode");
return { content: [{ type: "text", text: JSON.stringify({ success: true, data: [] }) }] };
} catch (error) {
return { content: [{ type: "text", text: JSON.stringify({ error: error instanceof Error ? error.message : "Unknown error" }) }], isError: true };
}
});
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("MCP Server running on stdio");
}
main().catch(console.error);AI Vibe Coding in 4 steps
- 1
Initialize MCP Project Skeleton
Goal: Create a TypeScript project and install MCP SDK and Zod dependencies.
PromptInitialize a TypeScript project, install @modelcontextprotocol/sdk and zod. Create a src/mcp-server.ts file, import Server and StdioServerTransport, and set up basic service metadata (name: 'team-business-tools').Verify:
Run `npm run build` to ensure no compilation errors and that mcp-server.js is generated in the dist/ directory. - 2
Define Zod Tool Contract
Goal: Use Zod to define the input parameter schema for the query_business_data tool.
PromptIn mcp-server.ts, define a Zod schema containing query (string, min 1) and limit (number, int, 1-100, default 10). Use this schema for the inputSchema field of the tools/list request handler, ensuring the description is clear.Verify:
Manually call the tools/list interface and check if the returned JSON includes the correct Zod metadata in inputSchema. - 3
Implement stdio Communication and Log Isolation
Goal: Configure the stdio transport layer to ensure logs are output to stderr, not stdout.
PromptImplement the main function to connect to StdioServerTransport. Ensure all console.log calls are changed to console.error to avoid polluting the stdio protocol data stream. Add a startup log 'MCP Server running on stdio'.Verify:
Run the server and observe the terminal output to confirm logs appear in the stderr channel and stdout has no extraneous characters. - 4
Configure Cursor Integration and Security Boundaries
Goal: Create .cursor/mcp.json and configure environment variables and read-only mode.
PromptCreate .cursor/mcp.json, setting the command to 'node' and args to ['dist/mcp-server.js']. Set env to include API_BASE_URL, API_KEY, and READ_ONLY_MODE='true'. Ensure autoApprove is set to false.Verify:
Restart the MCP server in Cursor, check if the tool list appears, and attempt to call a tool to verify that read-only restrictions are enforced.
Pitfalls & fixes
- stdout Pollution: Any console.log will break the JSON-RPC stream; all logs must be redirected to stderr.
- Missing Environment Variable Injection: The ${API_KEY} in .cursor/mcp.json must be defined in system environment variables, or the server startup will fail.
- Uncaught Zod Parse Failure: ZodError must be caught with try-catch in tools/call; otherwise, uncaught exceptions will cause the server to crash.
FAQ
Why choose stdio over HTTP transport?
stdio requires no port management or firewall rules, making it suitable for local IDE integration. It also offers faster startup times and lower resource consumption.
How to debug MCP server connection issues?
Check if the .cursor/mcp.json path is correct and ensure dist/mcp-server.js exists. Consult the Cursor MCP log panel for detailed error messages.
How does the Zod schema affect AI call accuracy?
Clear describe fields and strict type constraints significantly reduce the probability of AI generating incorrect parameters, thereby improving tool call success rates.


