A comprehensive implementation and example collection for the Model Context Protocol (MCP), built with TypeScript and the FastMCP library.
This is a TypeScript project that demonstrates how to build MCP servers and clients using the @modelcontextprotocol/sdk and fastmcp libraries. It includes various examples of MCP tools, different transport mechanisms, and integration patterns with AI models.
- Multiple Transport Types: Support for both STDIO and HTTP Stream transports
- Rich Tool Examples: Comprehensive collection of MCP tools demonstrating different capabilities
- Authentication: Built-in authentication mechanisms
- Progress Reporting: Real-time progress updates for long-running operations
- Multi-content Support: Handle text, image, and audio content types
- Session Management: User session handling and context management
- Error Handling: Robust error handling with custom error types
- Logging: Comprehensive logging system
- Client/Server Examples: Both client and server implementations
fastmcp/
├── src/
│ ├── index.ts # Main MCP server with example tools
│ ├── httpServer.ts # HTTP server implementation
│ ├── jsonrpc/ # JSON-RPC implementation
│ ├── mcp-client/ # MCP client implementations
│ ├── mcp-host/ # Function calling host examples
│ ├── mcp-servers/ # Various MCP server examples
│ ├── stdio/ # STDIO chat implementations
│ └── samples/ # Additional example code
├── diagrams/ # Architecture diagrams
├── package.json # Dependencies and scripts
└── README.md # This file
- Node.js (v20 or higher)
- pnpm package manager
- Clone the repository:
git clone <repository-url>
cd fastmcp- Install dependencies:
pnpm install- Set up environment variables (optional):
cp .env.example .env
# Edit .env with your API keys if neededThe main server (src/index.ts) includes a comprehensive set of example tools:
# Run with auto-reload
pnpm mcp:dev
# Or run the HTTP stream server
pnpm mcp:raw-http-streampnpm mcp:dev- Run the main MCP server with auto-reloadpnpm mcp:raw-stdio- Run the STDIO server examplepnpm mcp:raw-http-stream- Run the HTTP stream server examplepnpm mcp:client- Run the MCP client examplepnpm mcp:fc-host- Run the function calling hostpnpm stdio:chat- Run the STDIO chat applicationpnpm build- Build the TypeScript projectpnpm test- Run tests
The main server includes several example tools:
- Basic Math:
add- Add two numbers - Health Calculator:
calculate_bmi- Calculate BMI - Weather:
get_weather- Get weather information (requires API key) - File Operations:
readFile,delete_file- File system operations - Media Generation:
generate_image,generate_audio- Media content examples - Progress Tracking:
download_file- Demonstrates progress reporting - Database:
load_data_from_db- Database operation simulation - System Info:
get_process_info- Process and session information
The server includes a simple authentication mechanism:
const server = new FastMCP({
name: "test-server",
version: "0.0.1",
authenticate: async (request) => {
const authHeader = request.headers["x-api-key"];
// Validate API key
if (token !== "1234567890" && token !== "abc") {
throw new Response(null, { status: 401 });
}
return { id: token === "1234567890" ? crypto.randomUUID() : "abc" };
},
});Tools are defined using Zod schemas for type safety:
server.addTool({
name: "example_tool",
description: "Description of what the tool does",
parameters: z.object({
input: z.string().describe("Description of the input parameter"),
}),
execute: async (args, context) => {
const { input } = args;
const { log, session, reportProgress } = context;
// Your tool logic here
return {
content: [
{
type: "text",
text: "Tool result",
},
],
isError: false,
};
},
});server.start({
transportType: "stdio",
});server.start({
transportType: "httpStream",
httpStream: {
port: 8080,
endpoint: "/api/mcp", // optional
},
});The server supports multiple content types:
- Text: Standard text responses
- Images: Base64-encoded images with MIME types
- Audio: Base64-encoded audio with MIME types
Use helper functions for media content:
import { imageContent, audioContent } from "fastmcp";
// From URL
const img = await imageContent({ url: "https://example.com/image.jpg" });
// From file path
const img = await imageContent({ path: "./image.jpg" });
// From buffer
const img = await imageContent({ buffer: imageBuffer });The project includes comprehensive error handling:
import { UserError } from "fastmcp";
// For user-facing errors
throw new UserError("File not found");
// For internal errors with logging
try {
// risky operation
} catch (error) {
log.error("Internal error", { error });
throw new UserError("An error occurred");
}pnpm buildpnpm testpnpm format
pnpm format:checkThe project demonstrates several MCP architectural patterns:
- Server-Client Communication: JSON-RPC over STDIO/HTTP
- Tool Registration: Dynamic tool registration with schema validation
- Session Management: User session handling across requests
- Progress Reporting: Real-time progress updates
- Content Handling: Multi-modal content support
- Error Propagation: Structured error handling
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
const client = new Client(
{
name: "example-client",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
const transport = new StdioClientTransport({
command: "tsx",
args: ["src/index.ts"],
});
await client.connect(transport);import { FastMCPSession } from "fastmcp";
const session = new FastMCPSession({
name: "function-calling-host",
version: "1.0.0",
mcpServers: [
{
name: "test-server",
command: "tsx",
args: ["src/index.ts"],
},
],
});
const result = await session.runTool("add", { a: 1, b: 2 });- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
ISC License
For questions and support, please refer to the Model Context Protocol documentation or open an issue in this repository.