食品上下文协议服务器

食品上下文协议(FCP)的Python参考实现,提供43种食品相关工具、双重传输(MCP + REST)和Gemini 3集成。

  • by Food-Context-Protocol
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 Food-Context-Protocol/fcp-gemini-server

使用说明

FCP Gemini服务器

Gemini 3电源参考实现 食品环境协议

协议规范 · 尝试API · 文档


概述

这是 参考实现 Python中的食物上下文协议(FCP)。它演示了如何实现FCP的43个工具、双传输(MCP+REST)和Gemini 3集成。

对于 协议规范,请参阅: 食品环境协议/fcp

开发披露:由人工智能编码工具(Claude Code、GitHub Copilot、Cursor/Codex、Jules、Firebase Studio、Gemini API)协助开发以实现。核心架构、设计和功能都是原创作品。

⚠️ 法律免责声明:FCP提供人工智能生成的食品信息 仅供参考。这不是医疗、营养或健康建议。在未经验证的情况下,不要依赖人工智能进行过敏原检测、食品安全或药物与食品的相互作用。看 法律.md 完整的免责声明。

特性

  • ✅ 43 MCP工具 -营养、食谱、安全、库存、计划
  • ✅ 双重运输 -MCP标准输出+REST HTTP API
  • ✅ 100%测试覆盖率 -2981项测试通过
  • ✅ Gemini 3集成 -15+功能(多模式、基础、思考、Live API)
  • ✅ 类型安全 -所有输入/输出的Pydantic模式
  • ✅ 自动生成的SDK -Python+TypeScript通过Fern

快速开始

先决条件

安装

# Clone repository
git clone https://github.com/Food-Context-Protocol/fcp-gemini-server.git
cd fcp-gemini-server

# Install dependencies
make install

# Configure
cp .env.example .env
# Edit .env and add your GEMINI_API_KEY

跑

# HTTP Server (for web/mobile apps)
make dev-http
# Server runs on http://localhost:8080

# MCP Server (for Claude Desktop, CLI tools)
make run-mcp

# Run tests
make test

试试看

# Health check
curl http://localhost:8080/health

# Analyze a meal photo
curl -X POST http://localhost:8080/analyze \
  -H "Content-Type: application/json" \
  -d '{
    "image_url": "https://images.unsplash.com/photo-1546069901-ba9599a7e63c"
  }'

# Check food recalls
curl "http://localhost:8080/mcp/check_food_recalls?food_item=romaine+lettuce"

# List all MCP tools
curl http://localhost:8080/mcp/tools

MCP客户端集成

克劳德桌面

看 CLAUDE.md 有关完整的设置说明。

{
  "mcpServers": {
    "fcp": {
      "command": "uv",
      "args": ["--directory", "/path/to/fcp-gemini-server", "run", "python", "-m", "fcp.server"],
      "env": {
        "GEMINI_API_KEY": "your_key",
        "FCP_TOKEN": "your_token"
      }
    }
  }
}

Gemini CLI扩展

为Gemini CLI安装FCP扩展:

# Install extension
gemini extensions install ./gemini-extension

# Configure with your credentials
gemini extensions config fcp

# Use it
gemini
> /fcp:recent 5
> /fcp:search "that amazing ramen"
> /fcp:profile month

看 gemini扩展/README.md 对于所有可用命令。

建筑

┌─────────────┐
│   Clients   │  (CLI, Web, Mobile, Claude Desktop)
└──────┬──────┘
       │
       │  FCP Protocol (MCP stdio or REST HTTP)
       │
┌──────▼──────────────────────────────┐
│   FCP Server (This Repo)            │
│   - 43 Tool Implementations          │
│   - Pydantic Schema Validation      │
│   - Rate Limiting & Security        │
└──────┬──────────────────────────────┘
       │
       │  Google AI Python SDK
       │
┌──────▼──────────────────────────────┐
│   Gemini 3 Flash & Pro              │
│   - Multimodal Vision               │
│   - Function Calling                │
│   - Google Search Grounding         │
│   - Extended Thinking               │
│   - Code Execution                  │
│   - Live API                        │
└─────────────────────────────────────┘

项目结构

server/
├── src/fcp/
│   ├── tools/               # 43 MCP tool implementations
│   │   ├── nutrition/       # Meal analysis, logging
│   │   ├── recipes/         # Recipe search, scaling
│   │   ├── safety/          # Recall checks, allergens
│   │   ├── inventory/       # Pantry management
│   │   └── planning/        # Meal suggestions
│   ├── routes/              # REST API endpoints
│   │   └── schemas.py       # Pydantic response models
│   ├── services/            # External service clients
│   │   ├── gemini/          # Gemini 3 integration
│   │   ├── database.py      # SQLite persistence
│   │   └── fda.py           # OpenFDA integration
│   ├── security/            # Auth, rate limiting, validation
│   └── api.py               # FastAPI application
├── tests/                   # 100% branch coverage
│   ├── unit/                # Fast, hermetic tests
│   └── integration/         # E2E workflow tests
├── docs/                    # Implementation docs
└── Makefile                 # Common commands

Gemini 3集成

多模态视觉

# Analyze food photo
from fcp.services.gemini import GeminiClient

client = GeminiClient()
result = await client.analyze_image(
    image_url="https://example.com/food.jpg",
    prompt="Extract nutrition information"
)

函数调用

# Structured extraction with typed schemas
tools = [
    types.Tool(function_declarations=[
        types.FunctionDeclaration(
            name="log_meal",
            description="Log a meal with nutrition data",
            parameters=MealLogSchema
        )
    ])
]

谷歌搜索暂停

# Real-time FDA recall checks
response = await client.generate_content(
    prompt="Check if romaine lettuce has recalls",
    config=types.GenerateContentConfig(
        tools=[types.Tool(google_search_retrieval={})]
    )
)

可用命令

make install          # Install dependencies (uv sync)
make test             # Run tests with 100% coverage
make test-quick       # Run tests without coverage
make dev-http         # Start HTTP API with hot-reload
make run-mcp          # Start MCP stdio server
make lint             # Lint code with ruff
make format           # Format code with ruff
make typecheck        # Type check with mypy
make coverage         # Generate coverage report
make sdk              # Regenerate OpenAPI spec + SDKs

配置

所需的环境变量

变量 描述
GEMINI_API_KEY Google Gemini API密钥来自 ai.google.dev

可选环境变量

变量 描述 默认值
DATABASE_BACKEND 数据库后端(sqlite 或 firestore) sqlite
DEMO_MODE 启用演示模式(无需身份验证) false
DATABASE_URL SQLite数据库路径(仅限SQLite后端) sqlite:///data/fcp.db
GOOGLE_CLOUD_PROJECT GCP项目ID(仅限firestore后端) -
LOG_LEVEL 日志记录级别 INFO
RATE_LIMIT_PER_MINUTE API费率限制 60

看 .env.example 了解完整的配置选项。

数据库后端选择

服务器支持两个数据库后端:

SQLite(默认) -最有利于当地发展:

# Uses local SQLite database at data/fcp.db
DATABASE_BACKEND=sqlite
make dev-http

云火库 -对于Cloud Run上的生产:

# Install Firestore dependencies
uv sync --extra firestore

# Configure GCP project
export DATABASE_BACKEND=firestore
export GOOGLE_CLOUD_PROJECT=your-project-id

# For local testing, use service account credentials
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json

# Or use gcloud CLI default credentials
gcloud auth application-default login

# Start server
make dev-http

后端是根据以下内容自动选择的 DATABASE_BACKEND 环境变量。所有43个MCP工具在任一后端上的工作方式都是相同的。

测试

# Run all tests with coverage (enforces 100%)
make test

# Run specific test file
pytest tests/unit/tools/test_nutrition.py -v

# Run core integration tests (backend-agnostic, sqlite)
RUN_INTEGRATION=1 DATABASE_BACKEND=sqlite pytest tests/integration/ -m "core and integration"

# Run external integration tests (USDA/FDA/maps/places), opt-in
RUN_INTEGRATION=1 RUN_EXTERNAL_INTEGRATION=1 DATABASE_BACKEND=sqlite pytest tests/integration/ -m "external and integration"

# Run full integration suite
RUN_INTEGRATION=1 RUN_EXTERNAL_INTEGRATION=1 DATABASE_BACKEND=sqlite pytest tests/integration/

# Watch mode during development
pytest-watch

部署

看 docs/deployment-guide.md 部署到:

  • 谷歌云运行
  • Docker容器
  • Kubernetes
  • 本地服务器

使用Firestore快速部署到Cloud Run:

gcloud run deploy fcp-api \
  --source . \
  --region us-central1 \
  --allow-unauthenticated \
  --set-env-vars GEMINI_API_KEY=your-key,DATABASE_BACKEND=firestore,GOOGLE_CLOUD_PROJECT=your-project-id

备注:Cloud Run会自动使用应用程序默认凭据,因此不需要服务帐户密钥。确保Cloud Run服务帐户具有Firestore权限(roles/datastore.user).

贡献

我们欢迎捐款!查看主 贡献.md 用于:

  • 行为准则
  • 开发工作流程
  • 测试要求
  • 拉取请求流程

协议规范

此实现遵循食品上下文协议规范:

📖 视图规格

相关存储库

许可证

Apache-2.0-见 许可证 软件许可证和 法律.md 免责声明


Reference Implementation | Food Context Protocol
Like Stripe for payments, FCP for food AI 🍽️