营养数据库查询服务

一个提供智能访问USDA营养数据库的MCP服务器,可将复杂的营养数据转化为对话式查询,获取关于食物成分、营养含量和饮食分析的权威答案。

  • by HemantaPatil
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 HemantaPatil/mcp_postgres

使用说明

美国农业部营养数据库MCP服务器

一个全面的模型上下文协议(MCP)服务器,通过Claude Desktop等人工智能助手提供对美国农业部营养数据库的智能访问。将复杂的营养数据转换为对话式查询,并获得有关食物成分、营养成分和饮食分析的权威答案。

<N这提供了什么

  • = Smart Food Search - Find foods by keywords across 7,146+ items
  • =Ę Complete Nutrition Profiles - Get detailed nutrition data for any food
  • – Food Comparisons - Compare nutritional content between foods
  • =Ş Nutrient-Focused Discovery - Find foods highest in specific nutrients
  • =Â Category Browsing - Explore foods by category (24 major groups)
  • 科学 数据 访问 -直接访问美国农业部权威的营养数据库

=€快速入门

先决条件

  • Python 3.13+
  • 加载了USDA营养数据库的PostgreSQL
  • Claude Desktop(推荐)或MCP兼容客户端

安装

  1. 克隆存储库:

    git clone https://github.com/your-username/usda-mcp-server.git
    cd usda-mcp-server
    
  2. 安装依赖项:

    # Using pip
    pip install -r requirements.txt
    
    # Using uv (recommended)
    uv sync
    
  3. 配置数据库连接:

    在中编辑数据库配置 main.py 如果需要:

    db_config = {
        "host": "localhost",
        "port": 5432,
        "database": "usda",
        "user": "postgres",
        "password": "postgres"
    }
    
  4. 配置Claude桌面:

    添加到您的 claude_desktop_config.json:

    {
      "mcpServers": {
        "usda-postgres": {
          "command": "python",
          "args": ["/absolute/path/to/main.py"]
        }
      }
    }
    
  5. Start using:

    Restart Claude Desktop and ask questions like:

    • "Find foods high in protein"
    • "Compare the nutrition of chicken and salmon"
    • "What are the different types of apples in the database?"

=ŕ Available Tools

The MCP server provides 10 specialized tools:

Core Database Tools

Tool Description
execute_query 在数据库上执行自定义SQL查询
list_tables 列出所有可用的数据库表
describe_table 获取任何表的架构信息
get_table_sample 查看任何表中的示例数据

营养专用工具

工具 说明
search_foods 按名称/描述中的关键字搜索食物
get_nutrition_profile 获取特定食物的完整营养数据
get_foods_by_category 浏览特定类别的食物
get_food_categories 列出所有食品类别及其计数
compare_foods_nutrition 比较多种食物的营养
find_foods_high_in_nutrient 寻找特定营养素含量最高的食物

=克劳德桌面集成示例

寻找高蛋白食物

食物之间的营养比较

交互式食品搜索

> 测试

方法1:自动化测试套件

python test_mcp_server.py

此综合测试脚本验证:

  • 数据库连接
  • 所有工具功能
  • 性能基准测试
  • 交互式演示

方法2:MCP检查器(Web UI)

# Install MCP Inspector
npm install -g @modelcontextprotocol/inspector

# Launch web interface
mcp-inspector python main.py

打开 http://localhost:5173 以交互方式浏览工具和测试。

方法3:命令行测试

# Install MCP CLI
npm install -g @modelcontextprotocol/cli

# List available tools
mcp list-tools python main.py

# Test a specific tool
mcp call-tool python main.py search_foods '{"keyword": "apple", "limit": 5}'

方法4:直接Python测试

import asyncio
from main import mcp

async def test():
    result = await mcp.call_tool("search_foods", {"keyword": "chicken"})
    print(result)

asyncio.run(test())

=Ę数据库概述

美国农业部数据库包含:

表 行 描述
food_des 7146 食品描述和元数据
nut_data 253825 每种食物/营养素的营养价值
nutr_def 136 营养素定义和单位
fd_group 24 食品类别分类
data_src 366 Scientific references and sources
Others 5,100+ Supporting data (weights, footnotes, etc.)

Total: 368,416+ records of authoritative nutrition data

Key Statistics

  • 7,146 foods across 24 major categories
  • 136 different nutrients tracked (vitamins, minerals, macronutrients)
  • Most tracked nutrient: Energy (6,746 foods have calorie data)
  • Largest category: Vegetables and Vegetable Products (788 foods)
  • Data sources: 366 scientific studies and references

<× Architecture

Technology Stack

  • Python 3.13+ with asyncio for high-performance async operations
  • FastMCP for clean, decorator-based tool definitions
  • asyncpg for high-performance PostgreSQL connectivity
  • Connection pooling for efficient database resource management

Key Components

# MCP Server with tool decorators
mcp = FastMCP("usda-postgres")

@mcp.tool()
async def search_foods(keyword: str, limit: int = 20) -> str:
    """Search for foods by keyword"""
    # Implementation with optimized queries

Performance Features

  • Connection pooling for database efficiency
  • Async operations for concurrent request handling
  • Optimized SQL queries with proper indexing
  • JSON responses with structured data formatting

=' Configuration

Database Connection

Update main.py database configuration as needed:

db_config = {
    "host": "localhost",        # Database host
    "port": 5432,              # PostgreSQL port  
    "database": "usda",        # Database name
    "user": "postgres",        # Database user
    "password": "postgres"     # Database password
}

Claude Desktop Setup

Location of config file by OS:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json

= Troubleshooting

Common Issues

"Database connection failed"

# Check if PostgreSQL is running
pg_ctl status

# Verify database exists
psql -h localhost -U postgres -l | grep usda

# Test connection
psql -h localhost -U postgres -d usda -c "SELECT COUNT(*) FROM food_des;"

"No module named 'mcp'"

# Install dependencies
pip install -r requirements.txt
# or
uv sync

"Tools not appearing in Claude Desktop"

  1. Verify absolute path in config file
  2. Restart Claude Desktop completely
  3. Check server logs: python main.py 2>&1 | tee server.log

Performance Issues

# Check database indexes
psql -h localhost -U postgres -d usda -c "SELECT schemaname, tablename, indexname FROM pg_indexes WHERE schemaname = 'public';"

=Č Performance Benchmarks

Based on testing with the included test suite:

  • Average response time: ~70ms per query
  • Concurrent requests: Handles 5+ simultaneous requests efficiently
  • Database queries: Optimized with proper indexing and connection pooling
  • Memory usage: Efficient with connection pooling and async operations

< 使用案例

面向营养学家和营养师

  • 快速查找综合营养数据
  • 比较食物以制定膳食计划
  • 寻找特定营养素的最佳来源
  • 生成基于证据的建议

对于研究人员

  • 访问权威的美国农业部营养数据
  • 分析不同食品类别的营养模式
  • 有效交叉参考多种营养素
  • 导出数据以供进一步分析

面向注重健康的消费者

  • 做出明智的食物选择
  • 寻找富含所需营养的食物
  • 比较替代品的营养价值
  • 了解食物成分

食品工业

  • 分析竞争产品
  • 制定针对营养目标的食谱
  • 确保准确的营养标签
  • 研究成分替代品

=ă Roadmap

计划的功能

  • [ ] 配方分析 -计算完整食谱的营养
  • [ ] 饮食搭配 -寻找符合特定饮食要求的食物
  • [ ] 份量计算 -在不同份量之间转换
  • [ ] 趋势分析 -不同食品类别的营养模式
  • [ ] 导出功能 -查询结果的CSV/Excel导出

技术改进

  • [ ] 缓存层 用于频繁访问的数据
  • [ ] 全文搜索 更复杂的食品发现
  • [ ] GraphQL接口 用于灵活的数据查询
  • [ ] 实时更新 美国农业部发布新数据
  • [ ] Docker Support for easier deployment

> Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Development Setup

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Install dependencies: uv sync
  4. Run tests: python test_mcp_server.py
  5. Make your changes
  6. Run tests again to ensure everything works
  7. Submit a pull request

=Ý License

This project is licensed under the MIT License - see the LICENSE file for details.

=O Acknowledgments

  • USDA for maintaining the comprehensive nutrition database
  • Anthropic for developing the Model Context Protocol
  • PostgreSQL team for the robust database system
  • FastMCP developers for the excellent Python framework

=Ú Additional Resources

=Ţ Support

If you encounter any issues or have questions:

  1. Check the Troubleshooting section
  2. Run the test suite: python test_mcp_server.py
  3. Check existing Issues
  4. Create a new issue with detailed information

Built with d for the nutrition and AI communities

Making authoritative nutrition data accessible through intelligent AI conversations