前言

基于MCP协议,用300行代码搭建地图大脑Agent。

技术架构

用户输入 → LLM解析 → MCP调度 → 地图API → 结果生成

核心代码

1. MCP Server定义

```typescript
const server = new Server({
  name: 'map-brain-server',
  version: '1.0.0'
});

server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    { name: 'search_nearby', description: '搜索附近POI' },
    { name: 'get_heatmap', description: '获取人流热力' },
    { name: 'plan_route', description: '规划路线' }
  ]
}));
  1. 地图API实现
export async function searchNearby(params) {
  const res = await axios.get('https://apis.map.qq.com/ws/place/v1/search', {
    params: { ...params, key: TENCENT_KEY }
  });
  return res.data;
}
  1. LLM意图解析
export async function parseIntent(userInput) {
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [
      { role: 'system', content: '解析用户意图' },
      { role: 'user', content: userInput }
    ],
    response_format: { type: 'json_object' }
  });
  return JSON.parse(response.choices[0].message.content);
}
  1. 主程序
async function main() {
  const userInput = '附近人少的咖啡馆';
  const intent = await parseIntent(userInput);
  const result = await searchNearby(intent.parameters);
  const response = await generateResponse(userInput, result);
  console.log(response);
}

运行测试

npx ts-node index.ts "附近人少的咖啡馆"

输出:

为您找到3家咖啡馆
推荐第1家,人少适合办公
总结
掌握技能:

MCP协议工具定义
LLM意图解析
地图API集成
Agent多工具协同

更多推荐