This topic uses the Cook MCP to show how to build a custom Model Context Protocol (MCP) service with the Tuya MCP SDK. It also shows how an AI agent orchestrates multiple tools, including external data sources such as weather and Amap APIs, IoT devices such as ovens and rice cookers, and a recipe knowledge base.
Key capabilities include:
| Capability | Implementation |
|---|---|
| Multi-source recommendation | Combines weather, location, user preferences, and other contextual information to generate personalized recommendations. |
| IoT device linkage | Controls smart kitchen appliances through MCP tools. |
| Enhanced knowledge base retrieval | Retrieves recipe knowledge with Retrieval-Augmented Generation (RAG). |
| Custom MCP service | Registers tools and connects services through the Tuya MCP SDK. |
┌─────────────────────────────────────────────────────┐
│ AI Agent │
│ ┌───────────┬───────────┬───────────┬───────────┐ │
│ │ Weather │ Amap │ Smart home│ Cook MCP │ │
│ └─────┬─────┴─────┬─────┴─────┬─────┴─────┬─────┘ │
└────────┼───────────┼───────────┼───────────┼────────┘
│ │ │ │
Weather API Amap API IoT devices Custom MCP service
│
┌────────────┼────────────┐
│ │ │
Recipe knowledge base LLM engine Cache
cook/__main__.py)| Design feature | Description |
|---|---|
| Dependency management | Coordinates the startup sequence and resolves component dependencies. |
| Health check | Monitors service status and supports automatic recovery. |
| Resilience | Automatically reconnects after network interruptions using exponential backoff. |
| Signal handling | Supports graceful shutdown and automatic resource cleanup. |
cook/recipe_mcp/recipe_mcp_server.py)| Design feature | Description |
|---|---|
| Dual protocol support | Supports both HTTP APIs and WebSocket connections for different client scenarios. |
| Declarative tool registration | Registers tools with decorators to simplify development. |
| Type safety | Validates parameters with Pydantic models. |
| Health monitoring | Provides built-in health checks and performance metrics. |
cook/recipe_agent.py)| Design feature | Description |
|---|---|
| Data proxy | Provides a unified interface for accessing multiple data sources and abstracts away underlying differences. |
| Large language model (LLM) proxy | Encapsulates the recommendation logic and supports scenario-based recommendations with deduplication. |
| Multi-level cache | Reduces repeated network requests and improves response performance. |
| Configuration management | Supports flexible runtime configuration. |
src/mcp_sdk/)| Design feature | Description |
|---|---|
| Authentication mechanism | Uses signature-based authentication and access control. |
| Connection management | Manages WebSocket connection pools and heartbeat detection. |
| Message routing | Dispatches and processes messages efficiently. |
| Fault recovery | Automatically reconnects and restores status after network failures. |
For the complete source code, see GitHub.
The Tuya MCP SDK manages communication between a custom MCP service and the Tuya AI Cloud. It provides the following capabilities:
# Core configurations of the Tuya MCP SDK
config = {
"client_id": "<Client ID assigned by the platform>",
"client_secret": "<Client Secret assigned by the platform>",
"data_center": "<Data center>", # For example, CN, US, or EU.
}
from fastmcp import FastMCP
mcp = FastMCP("cook-service")
@mcp.tool()
def get_recipes_by_category(category: str) -> list:
"""Query recipes by category."""
# Business logic implementation
pass
@mcp.tool()
def recommend_recipes_for_dinner(
people_count: int,
weather: str,
location: str
) -> list:
"""Recommend dinner recipes based on multidimensional context."""
# Integrate factors such as weather, location, and party size.
pass
Register tools declaratively with decorators. The SDK automatically:
| Dependency | Version |
|---|---|
| Python | 3.10+ |
| LLM | qwen3-30b-a3b-instruct-2507 (Get an API key from Alibaba Cloud) |
| Network | Access to the Tuya platform and the LLM API |
| Resource | Where to access |
|---|---|
| Tuya Developer account | Tuya Developer Platform |
| MCP management | MCP Management |
| Agent management | My Agent |
| MCP documentation | Custom MCP Services |
# 1. Clone the project
git clone https://github.com/flyhawk1010/cook-mcp
cd cook-mcp
# 2. Install dependencies
pip install -r requirements.txt
# 3. Configure environment variables (MCP SDK authentication information and LLM API key)
cp .env.example .env
# Edit the .env file and fill in the configuration.
# 4. Start the service
python -m cook
Add a custom MCP in the Tuya Developer Platform > MCP Management.
| Item | Value |
|---|---|
| Service name | Cook MCP |
| Service description | AI-powered recipe recommendations and meal planning based on weather, location, party size, and other context. |
Add a data center on the service details page, and get the client_id and client_secret for SDK initialization.
After the service starts, open the service details page and verify that the connection status is Connected.
The platform provides an online debugging feature for testing registered tools.
// Test case 1: Query by category
{
"tool": "get_recipes_by_category",
"params": { "category": "Aquatic products" }
}
// Test case 2: Context-aware recommendation
{
"tool": "recommend_recipes_for_dinner",
"params": {
"people_count": 4,
"weather": "Sunny, 32°C",
"location": "Hangzhou"
}
}
After debugging succeeds, the agent can call tools dynamically at runtime.
A recipe knowledge base supplies domain knowledge to the agent via RAG, improving recommendation quality and accuracy.
| Dimension | Best practice |
|---|---|
| Content format | Uses consistent fields, including recipe name, ingredients, cooking temperature, cooking time, and steps. |
| Classification | Categorizes recipes by scenario, such as breakfast, lunch, dinner, meat, vegetarian, quick meals, and slow-cooked dishes. |
| Device compatibility | Specifies the supported appliance types and models, such as oven temperature ranges and rice cooker cooking modes. |
| Data import | Supports both manual entry and batch import. |
Create → Edit (Draft) → Publish → Maintain and update
↓
Bind to the agent
The platform supports state management (published, draft, and unpublished), content search, and filtering.
The agent integrates the following skills to support multi-tool orchestration.
| Skill type | Skill | Purpose |
|---|---|---|
| Official skill | Weather | Provides weather information for recipe recommendations. |
| Official skill | Amap keyword search | Recommends nearby grocery stores and restaurants. |
| Official skill | Device control | Controls smart kitchen appliances to perform cooking tasks. |
| Custom MCP | Cook MCP | Provides recipe search, recipe recommendations, and meal planning. |
| Knowledge base | Recipe knowledge base | Supplies domain-specific knowledge through RAG. |
User input: What should I cook for dinner for four people today?
User input
→ Agent identifies the intent
→ Call the weather skill to get the current weather
→ Call [Cook MCP: recommend_recipes_for_dinner]
Parameters: {people_count: 4, weather: "Sunny, 32°C", location: "Hangzhou"}
→ Integrate knowledge base retrieval results
→ Generate a recommendation
The AI agent automatically determines the tool call sequence. Outputs from one tool can be used as inputs for subsequent tool calls, enabling seamless data flow across multiple tools.
The agent prompt should cover:
| Dimension | Content |
|---|---|
| Role setting | Acts as a professional cooking assistant familiar with Chinese and Western cuisine. |
| Core task | Recommends recipes based on user requirements and contextual information. |
| Constraints | Considers factors such as allergens, party size, and weather conditions. |
| Tool usage strategy | Specifies when to call the weather skill, Amap keyword search, Cook MCP, and device control. |
| Dimension | Tuya MCP SDK | Value |
|---|---|---|
| Access method | Registers tools by using decorators. | Offers a shallow learning curve and a native Python workflow. |
| Protocol support | Uses persistent WebSocket connections. | Supports low-latency bidirectional communication and connection reuse. |
| Reliability | Automatically reconnects with exponential backoff. | Improves service availability during transient network failures. |
| Security | Uses signature-based authentication and access control. | Meets enterprise-grade security standards. |
| Debugging | Supports both online debugging and local development. | Accelerates iterative validation. |
Multi-tool orchestration enables the agent to combine information from multiple tools and services automatically.
| Stage | Recommendation |
|---|---|
| Architecture | Adopts a microservice architecture to decouple services and support independent scaling. |
| Tool definition | Provides clear tool descriptions and accurate parameter definitions for more accurate tool selection and invocation. |
| Exception handling | Handles all expected exceptions and implements retry mechanisms for transient failures. |
| Performance | Uses multi-level caching to reduce redundant computations and external API requests. |
| Testing | Tests locally, verifies on the platform, and expands features progressively. |
| Observability | Enables detailed logging to simplify troubleshooting and trace end-to-end tool calls. |
Is this page helpful?
YesFeedbackIs this page helpful?
YesFeedback