AI数据查询服务

一个基于Go构建的MCP协议服务器,为AI代理提供Taylor Swift相关数据(专辑、歌曲、巡演)的低延迟查询服务,适用于需要快速访问结构化音乐数据的AI系统。

  • by inirah02
  • Go
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 inirah02/mcp-swiftie-server

使用说明

MCP Swiftie服务器

Go内置的模型上下文协议(MCP)服务器,为AI代理提供对Taylor Swift数据(专辑、歌曲、巡演)的访问。此演示展示了MCP协议实现、Go并发模式和AI系统的低延迟数据检索。


快速开始

先决条件

  • 转到1.21+ (下载)
  • 无需数据库(使用内存中的模拟数据)

安装和设置

# 1. Clone or create the project
mkdir mcp-swiftie-server
cd mcp-swiftie-server

# 2. Initialize Go module
go mod init github.com/yourusername/mcp-swiftie-server

# 3. Install dependencies
go mod tidy

# 4. Build server and client
./build.sh

# You should see:
# ✅ Build successful!
# -rwxr-xr-x  1 user  staff   7.3M mcp-client
# -rwxr-xr-x  1 user  staff   8.2M mcp-server

项目结构

mcp-swiftie-server/
├── types.go              # MCP protocol types & data models
├── presto.go            # Mock query engine (Presto simulator)
├── handlers.go          # MCP tool handlers & concurrent execution
├── main.go              # HTTP server, WebSocket, metrics
├── benchmark_test.go    # Performance benchmarks
├── examples/
│   └── simple_client.go # Demo client
├── build.sh             # Build script
├── Makefile             # Convenience commands
├── go.mod               # Go dependencies
└── README.md            # This file

运行演示

终端1:启动服务器

./mcp-server

# Output:
# [INFO] 🎤 MCP Swiftie Server starting...
# [INFO] Registered 5 tools: [list_tables query_albums query_songs analyze_tours streaming_query]
# [INFO] Server listening on :9000
# [INFO] Ready for connections

刚刚发生的事情:

  • 服务器在~50ms内启动
  • 注册了5个MCP工具(代理可以调用的功能)
  • WebSocket侦听器在端口9000上启动

终端2:运行客户端

./mcp-client

# Output:
# Connected to MCP Swiftie Server
# Listing available tools...
# Querying Taylor Swift albums...
# Query completed in 51.4ms
# Testing streaming query...
# Streaming query completed in 134.9ms
# Analyzing tour data...
# Demo completed successfully!

您所看到的:

  • MCP协议握手(工具发现)
  • 同步查询执行(往返51ms)
  • 批量结果的流式查询(共134ms)
  • 旅游收入分析

终端3:检查服务器运行状况

curl http://localhost:9000/metrics | jq

# Output:
{
  "queries_executed": 8,
  "avg_latency_ms": 58.3,
  "active_goroutines": 14,
  "uptime_seconds": 127
}

关键指标:

  • 平均延迟58.3ms -快速响应时间
  • 14个活跃的goroutines -轻量级并发(28KB内存)
  • 正常运行时间跟踪 -服务器稳定性监控

运行基准

运行所有基准测试

make bench

# Output:
# Running benchmarks...
# BenchmarkSingleQuery-8                      2000    550123 ns/op
# BenchmarkConcurrentQueries/Concurrency-10     500   2345678 ns/op
# BenchmarkConcurrentQueries/Concurrency-50     200   7654321 ns/op
# BenchmarkConcurrentQueries/Concurrency-100    100  15234590 ns/op
# BenchmarkStreamingQuery-8                   1000   1123456 ns/op
# Benchmark results saved to benchmark_results.txt

运行特定基准测试(100个并发查询)

go test -bench=BenchmarkConcurrentQueries/Concurrency-100 -benchtime=3s

# Output:
# BenchmarkConcurrentQueries/Concurrency-100-8    200   15234590 ns/op
# PASS
# ok    github.com/yourusername/mcp-swiftie-server    4.127s

释义:

  • 200次迭代=4秒内总共查询20000次
  • 每批15.2ms 100个查询
  • 5000次查询/秒 持续吞吐量

使用种族检测器跑步(安全检查)

go test -race -v

# Checks for data races in concurrent code
# Should pass with no warnings

性能指标

关键数字(在苹果M1 MacBook Pro上)

度量 值 比较
单次查询延迟 550µs ~0.5ms
100个并发查询 15.2ms 每次查询约150µs
内存(100个并发) 150KB 每个查询1.5KB
二进制大小 8.2MB 无依赖关系
冷启动时间 50毫秒与1.5秒Python
活跃的goroutines 14 28KB总内存
持续吞吐量 5000 q/s 模拟延迟为50ms

可用的MCP工具

1. list_tables

列出数据库中所有可用的表。

例子:

{
  "name": "list_tables",
  "arguments": {}
}

答复:

{
  "columns": ["table_name"],
  "rows": [["albums"], ["songs"], ["tours"]],
  "row_count": 3
}

2. query_albums

使用可选的时代过滤查询Taylor Swift专辑。

例子:

{
  "name": "query_albums",
  "arguments": {
    "era": "Pop"  // Optional: filter by era
  }
}

答复:

{
  "columns": ["id", "title", "release_year", "era", "sales_millions", "genre"],
  "rows": [
    ["ALB005", "1989", 2014, "Pop", 10, "Synth Pop"],
    ["ALB006", "Reputation", 2017, "Pop", 4, "Electropop"]
  ],
  "row_count": 2,
  "query_time_ms": 51
}

3. query_songs

使用流媒体和图表数据查询歌曲。

例子:

{
  "name": "query_songs",
  "arguments": {
    "min_streams": 1000  // Optional: minimum streams in millions
  }
}

4. analyze_tours

获取旅游收入和出勤数据。

答复包括:

  • 旅游名称和年份
  • 演出次数
  • 总出席人数
  • 收入(单位:百万)

有趣的事实: Eras Tour在数据集中产生了超过20亿美元的收入! 🎤


5. streaming_query

演示批量流式处理结果(适用于大型数据集)。

例子:

{
  "name": "streaming_query",
  "arguments": {
    "table": "songs"
  }
}

答复:

{
  "batches": 4,
  "total_rows": 20,
  "query_time": 134
}

服务器日志显示:

[DEBUG] Streaming batch 1 (5 rows)
[DEBUG] Streaming batch 2 (5 rows)
[DEBUG] Streaming batch 3 (5 rows)
[DEBUG] Streaming batch 4 (5 rows)

Makefile命令

make build    # Build server and client
make test     # Run tests with race detector
make bench    # Run benchmarks and save results
make clean    # Remove binaries and artifacts

🔍 监测和可观察性

健康检查端点

curl http://localhost:9000/health

# Response:
{"status":"healthy"}

度量端点(JSON)

curl http://localhost:9000/metrics

# Response:
{
  "queries_executed": 127,
  "avg_latency_ms": 58.3,
  "active_goroutines": 12,
  "uptime_seconds": 1847
}

实时观察指标

watch -n 1 'curl -s http://localhost:9000/metrics | jq'

# Updates every second with color-coded JSON

测试

运行所有测试

go test -v

# Includes:
# - Unit tests for handlers
# - Concurrency tests
# - Cancellation tests
# - Memory leak tests

运行覆盖率测试

go test -cover

# Shows percentage of code covered by tests

配置文件内存使用情况

go test -memprofile=mem.prof
go tool pprof mem.prof

# Interactive profiler for memory analysis

建筑亮点

为什么这个设计有效

1. 用于并发的Goroutines

// One goroutine per tool invocation
for _, tool := range tools {
    go func(t ToolInvocation) {
        results <- server.ExecuteTool(ctx, t)
    }(tool)
}
  • 轻量化: 每个goroutine 2KB堆栈
  • 可扩展性: 10000+goroutines=没问题
  • 简单: 没有线程池,没有执行器

2. 沟通渠道

// Type-safe message passing
results := make(chan Result, len(tools))
results <- executeQuery(query)  // Send
result := <-results             // Receive
  • 无需锁: 通道防止数据竞争
  • 可组合: 易于构建复杂模式
  • 缓冲: 适当时不堵塞

3. 取消的背景

ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()

select {
case <-ctx.Done():
    return ctx.Err()  // Clean shutdown
case results <- row:
    // Continue processing
}
  • 自动传播: 取消流程通过调用堆栈进行
  • 无泄漏: 当上下文取消时,Goroutines停止
  • 超时支持: 内置的截止日期管理

4. 原子度量(无锁)

var queriesExecuted atomic.Int64

queriesExecuted.Add(1)  // Concurrent-safe, no mutex
  • 快速: 每次操作约5纳秒
  • 安全: 无比赛条件
  • 低开销: 可忽略的性能影响

为什么选择Taylor Swift数据?

原因:

它的主题是SwiftieinTech,这是一个技术、创意和文化交汇处的跨平台社区。我最初是一份时事通讯,现在已经发展成为一个全球学习、指导和对话的空间。它支持技术深度,同时为讲故事、好奇心和快乐腾出空间。通过分散把关和“畏缩”,SwiftieinTech创造了访问权限,建立了信心,并反映了人们在当今技术中成长、建立和归属的不断发展的方式。
订阅时事通讯 & 在Instagram上查看

实际生产使用情况:

在生产环境中,将模拟数据与真实的Presto进行交换:

// Demo
func Query(sql string) []Row {
    return mockTaylorSwiftData.query(sql)
}

// Production
func Query(sql string) []Row {
    return prestoClient.Execute(sql)
}

MCP协议模式保持不变。


生产注意事项

这是一个 演示工程.对于生产,添加:

  • [ ] 认证 -JWT令牌、API密钥
  • [ ] 速率限制 -每用户查询限制
  • [ ] TLS/SSL -加密WebSocket连接
  • [ ] 结构化日志记录 -带有相关ID的JSON日志
  • [ ] 分布式跟踪 -OpenTetry集成
  • [ ] 真实数据库池 -Presto的连接池
  • [ ] 断路器 -依赖关系关闭时会快速失败
  • [ ] 多租户技术 -每个租户的数据隔离
  • [ ] 架构版本控制 -优雅地处理工具演变

了解更多

文档

  • MCP规范: https://modelcontextprotocol.io
  • 去并发: https://go.dev/blog/pipelines
  • Go中的WebSocket: https://pkg.go.dev/github.com/gorilla/websocket

相关项目

  • Presto Go客户端: https://github.com/prestodb/presto-go-client
  • 克劳德MCP服务器: https://github.com/anthropics/mcp-servers

故障排除

“无测试文件”错误

问题: make bench 显示 [no test files]

解决方案: 确保 benchmark_test.go 存在于根目录中。

ls benchmark_test.go
# If missing, re-download from the repo

“主重新声明”错误

问题: go test 失败,返回“main在此块中重新声明”

解决方案: simple_client.go 应该在 examples/ 目录,而不是根目录。

ls examples/simple_client.go  # Should exist
ls simple_client.go            # Should NOT exist

端口已在使用中

问题: 服务器出现故障,“地址已在使用中”

解决方案: 终止现有进程或更改端口。

# Find process on port 9000
lsof -ti:9000 | xargs kill -9

# Or use custom port
PORT=9001 ./mcp-server

内置于💜 Go社区和各地的Swifties。

“好久不见了” ✨