# Time MCP 使用文档
本文档介绍如何在其他 LLM 应用中集成和使用 time-mcp 服务器。
## 目录
- [概述](#概述)
- [前置要求](#前置要求)
- [MCP 服务器配置](#mcp-服务器配置)
- [在 OpenAI Responses API 中使用](#在-openai-responses-api-中使用)
- [在其他 LLM 应用中使用](#在其他-llm-应用中使用)
- [工具说明](#工具说明)
- [示例代码](#示例代码)
- [故障排查](#故障排查)
## 概述
Time MCP 是一个基于 Model Context Protocol (MCP) 的服务器,为 LLM 应用提供时间相关的工具。它通过标准化的 JSON-RPC 协议与 LLM 应用通信,支持两种传输方式:
- **HTTP 传输**(推荐):适用于远程部署和网络通信,支持 OpenAI Responses API
- **Stdio 传输**:适用于本地进程通信
## 前置要求
- Node.js 18 或更高版本
- 已安装并构建 time-mcp 服务器
- 了解 MCP 协议基础
## MCP 服务器配置
### 1. 构建服务器
首先,确保 time-mcp 服务器已构建:
```bash
cd time-mcp
pnpm install
pnpm build
```
### 2. 服务器启动方式
Time MCP 服务器支持两种传输模式:
#### HTTP 模式(推荐,用于 Responses API)
HTTP 模式适用于远程部署和网络通信,是使用 OpenAI Responses API 的推荐方式。
**启动命令:**
```bash
# 生产环境
TRANSPORT=http PORT=3000 HOST=0.0.0.0 MCP_PATH=/mcp node dist/index.js
# 开发环境
TRANSPORT=http PORT=3000 HOST=0.0.0.0 MCP_PATH=/mcp pnpm dev:http
```
**环境变量说明:**
- `TRANSPORT`: 传输类型,设置为 `http`
- `PORT`: HTTP 端口(默认: `3000`)
- `HOST`: 监听地址(默认: `0.0.0.0`)
- `MCP_PATH`: API 路径(默认: `/mcp`)
**使用 Docker 部署:**
```bash
# 使用 Docker Compose(推荐)
docker-compose up -d
# 或使用 Docker 命令
docker run -d \
--name time-mcp \
-p 3000:3000 \
-e TRANSPORT=http \
-e PORT=3000 \
-e HOST=0.0.0.0 \
-e MCP_PATH=/mcp \
time-mcp
```
服务器启动后,可以通过以下 URL 访问:
```
http://localhost:3000/mcp
```
#### Stdio 模式(本地进程通信)
Stdio 模式适用于本地进程通信,需要 LLM 应用作为父进程启动 MCP 服务器。
```bash
# 生产环境
node dist/index.js
# 开发环境
pnpm dev
```
## 在 OpenAI Responses API 中使用
OpenAI Responses API 是 OpenAI 最新推出的接口,直接支持远程 MCP 服务器,无需手动管理 MCP 客户端连接。这是使用 time-mcp 的**推荐方式**。
### 前置要求
1. 确保 time-mcp 服务器已以 HTTP 模式启动
2. 安装 OpenAI SDK(需要支持 Responses API 的版本)
```bash
pnpm add openai
```
### 基础使用
```typescript
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function useWithResponsesAPI() {
const response = await openai.responses.create({
model: 'gpt-4',
tools: [
{
type: 'mcp',
server_label: 'time-mcp',
server_url: 'http://localhost:3000/mcp', // MCP 服务器地址
},
],
input: '现在几点了?请告诉我当前的 UTC 时间。',
});
console.log('响应:', response.output);
return response.output;
}
// 使用示例
useWithResponsesAPI().catch(console.error);
```
### 完整示例:带错误处理
```typescript
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function chatWithTimeMCP() {
try {
const response = await openai.responses.create({
model: 'gpt-4',
tools: [
{
type: 'mcp',
server_label: 'time-mcp',
server_url: process.env.MCP_SERVER_URL || 'http://localhost:3000/mcp',
},
],
input: '现在几点了?请告诉我当前的 UTC 时间,并解释一下 Unix 时间戳的含义。',
});
console.log('最终响应:', response.output);
return response.output;
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.error('OpenAI API 错误:', error.status, error.message);
} else {
console.error('未知错误:', error);
}
throw error;
}
}
chatWithTimeMCP().catch(console.error);
```
### 配置多个 MCP 服务器
```typescript
async function useMultipleMCPServers() {
const response = await openai.responses.create({
model: 'gpt-4',
tools: [
{
type: 'mcp',
server_label: 'time-mcp',
server_url: 'http://localhost:3000/mcp',
},
// 可以添加更多 MCP 服务器
// {
// type: 'mcp',
// server_label: 'other-mcp',
// server_url: 'http://localhost:3001/mcp',
// },
],
input: '现在几点了?',
});
return response.output;
}
```
### 使用环境变量配置
```typescript
// .env
// OPENAI_API_KEY=your-api-key
// MCP_SERVER_URL=http://localhost:3000/mcp
import OpenAI from 'openai';
import dotenv from 'dotenv';
dotenv.config();
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function useWithEnvConfig() {
const response = await openai.responses.create({
model: 'gpt-4',
tools: [
{
type: 'mcp',
server_label: 'time-mcp',
server_url: process.env.MCP_SERVER_URL!,
},
],
input: '现在几点了?',
});
return response.output;
}
```
### 封装为可复用的工具类
```typescript
import OpenAI from 'openai';
class TimeMCPIntegration {
private openai: OpenAI;
private mcpServerUrl: string;
constructor(apiKey: string, mcpServerUrl: string = 'http://localhost:3000/mcp') {
this.openai = new OpenAI({ apiKey });
this.mcpServerUrl = mcpServerUrl;
}
async query(input: string, model: string = 'gpt-4') {
const response = await this.openai.responses.create({
model,
tools: [
{
type: 'mcp',
server_label: 'time-mcp',
server_url: this.mcpServerUrl,
},
],
input,
});
return response.output;
}
}
// 使用示例
async function example() {
const integration = new TimeMCPIntegration(
process.env.OPENAI_API_KEY!,
'http://localhost:3000/mcp'
);
const result = await integration.query('现在几点了?');
console.log('结果:', result);
}
example().catch(console.error);
```
### 生产环境部署
在生产环境中,建议:
1. **使用环境变量配置服务器地址**
2. **添加错误处理和重试机制**
3. **配置超时时间**
4. **使用 HTTPS**(如果部署在公网)
```typescript
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
timeout: 30000, // 30 秒超时
maxRetries: 3, // 最多重试 3 次
});
async function productionExample() {
const mcpServerUrl = process.env.MCP_SERVER_URL || 'http://localhost:3000/mcp';
// 确保使用 HTTPS(如果部署在公网)
const secureUrl = mcpServerUrl.replace('http://', 'https://');
try {
const response = await openai.responses.create({
model: 'gpt-4',
tools: [
{
type: 'mcp',
server_label: 'time-mcp',
server_url: secureUrl,
},
],
input: '现在几点了?',
});
return response.output;
} catch (error) {
// 错误处理和日志记录
console.error('请求失败:', error);
throw error;
}
}
```
## 工具说明
### getCurrentTime
获取当前 UTC 时间。
**参数**: 无
**返回格式**:
```json
{
"timestamp": "2024-01-01T12:00:00.000Z",
"iso": "2024-01-01T12:00:00.000Z",
"unix": 1704110400000
}
```
**字段说明**:
- `timestamp`: ISO 8601 格式的 UTC 时间字符串
- `iso`: 同 timestamp,ISO 8601 格式
- `unix`: Unix 时间戳(毫秒)
## 示例代码
完整示例代码请参考项目中的 `examples/` 目录(如果存在)。
### HTTP 模式基础示例
```typescript
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { HTTPClientTransport } from '@modelcontextprotocol/sdk/client/http.js';
async function basicHTTPExample() {
const transport = new HTTPClientTransport(new URL('http://localhost:3000/mcp'));
const client = new Client(
{
name: 'time-mcp-client',
version: '1.0.0',
},
{
capabilities: {},
}
);
await client.connect(transport);
try {
// 列出可用工具
const tools = await client.listTools();
console.log('可用工具:', tools.tools);
// 调用工具
const result = await client.callTool({
name: 'getCurrentTime',
arguments: {},
});
console.log('当前时间:', result.content[0]?.text);
} finally {
await client.close();
}
}
basicHTTPExample().catch(console.error);
```
### Stdio 模式基础示例(本地进程通信)
```typescript
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { spawn } from 'child_process';
async function basicStdioExample() {
const serverProcess = spawn('node', ['/path/to/time-mcp/dist/index.js'], {
stdio: ['pipe', 'pipe', 'pipe'],
});
const transport = new StdioClientTransport({
command: serverProcess.spawnfile,
args: [],
env: process.env,
});
const client = new Client(
{
name: 'time-mcp-client',
version: '1.0.0',
},
{
capabilities: {},
}
);
await client.connect(transport);
try {
// 列出可用工具
const tools = await client.listTools();
console.log('可用工具:', tools.tools);
// 调用工具
const result = await client.callTool({
name: 'getCurrentTime',
arguments: {},
});
console.log('当前时间:', result.content[0]?.text);
} finally {
await client.close();
serverProcess.kill();
}
}
basicStdioExample().catch(console.error);
```
## 故障排查
### 1. HTTP 服务器无法启动
**问题**: 执行 HTTP 模式启动命令时出错
**解决方案**:
- 确保已运行 `pnpm build` 构建项目
- 检查 Node.js 版本是否为 18+
- 检查端口是否被占用:`lsof -i :3000` 或 `netstat -tulpn | grep 3000`
- 检查环境变量是否正确设置
### 2. MCP 客户端连接失败(HTTP 模式)
**问题**: 客户端无法连接到 HTTP 服务器
**解决方案**:
- 确保服务器已启动并监听在正确的地址和端口
- 检查服务器 URL 是否正确(例如:`http://localhost:3000/mcp`)
- 使用 `curl http://localhost:3000/mcp` 测试服务器是否响应
- 检查防火墙设置
- 查看服务器日志获取详细错误信息
### 3. Responses API 无法连接 MCP 服务器
**问题**: OpenAI Responses API 无法连接到 MCP 服务器
**解决方案**:
- 确保 MCP 服务器 URL 可公开访问(如果 OpenAI 需要访问)
- 检查服务器是否支持 CORS(time-mcp 默认已配置)
- 验证服务器 URL 格式正确:`http://host:port/path`
- 检查网络连接和防火墙规则
- 查看服务器日志确认请求是否到达
### 4. Stdio 模式服务器无法启动
**问题**: 执行 stdio 模式启动命令时出错
**解决方案**:
- 确保已运行 `pnpm build` 构建项目
- 检查 Node.js 版本是否为 18+
- 检查文件路径是否正确
### 5. Stdio 模式客户端连接失败
**问题**: Stdio 模式客户端无法连接到服务器
**解决方案**:
- 确保服务器进程已正确启动
- 检查 stdio 管道是否正确配置
- 查看服务器错误日志(stderr)
### 6. 工具调用返回错误
**问题**: 调用工具时返回错误
**解决方案**:
- 检查工具名称是否正确(区分大小写)
- 检查参数格式是否符合 schema
- 查看服务器日志获取详细错误信息
### 7. OpenAI Responses API 集成问题
**问题**: Responses API 无法识别或调用 MCP 工具
**解决方案**:
- 确保 MCP 服务器 URL 可访问
- 检查 `server_label` 和 `server_url` 配置是否正确
- 验证服务器返回的工具列表格式是否符合 MCP 规范
- 查看 OpenAI API 响应中的错误信息
## 更多资源
- [Model Context Protocol 官方文档](https://modelcontextprotocol.io/)
- [OpenAI API 文档](https://platform.openai.com/docs/api-reference)
- [MCP SDK 文档](https://github.com/modelcontextprotocol/typescript-sdk)
## 许可证
ISC