Develop an AI Smart Kitchen Application with the Tuya MCP SDK

Last Updated on : 2026-07-08 08:57:13Copy for LLMView as MarkdownDownload PDF

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.

Architecture

System diagram

┌─────────────────────────────────────────────────────┐
│                   AI Agent                          │
│  ┌───────────┬───────────┬───────────┬───────────┐  │
│  │ Weather   │    Amap   │ Smart home│ Cook MCP  │  │
│  └─────┬─────┴─────┬─────┴─────┬─────┴─────┬─────┘  │
└────────┼───────────┼───────────┼───────────┼────────┘
         │           │           │           │
    Weather API   Amap API  IoT devices  Custom MCP service
                                                       │
                                          ┌────────────┼────────────┐
                                          │            │            │
                          Recipe knowledge base    LLM engine     Cache

Core components

Service launcher (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.

FastMCP service (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.

Unified proxy layer (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.

Tuya MCP SDK integration layer (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.

Tuya MCP SDK overview

SDK architecture

The Tuya MCP SDK manages communication between a custom MCP service and the Tuya AI Cloud. It provides the following capabilities:

  • Authentication: Uses signature-based request authentication.
  • Connection maintenance: Maintains persistent WebSocket connections with heartbeat keepalive.
  • Tool registration: Automatically registers locally defined tools with the platform.
  • Message routing: Routes tool call requests to the corresponding tool functions.

Key configuration parameters

# 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.
}

Register tools

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:

  • Extracts tool metadata, including the name, description, and parameter schema.
  • Validates parameters based on Python type hints.
  • Synchronizes the registered tools with the platform.

Prerequisites

Environment requirements

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

Platform resources

Resource Where to access
Tuya Developer account Tuya Developer Platform
MCP management MCP Management
Agent management My Agent
MCP documentation Custom MCP Services

Develop and deploy the service

Develop locally

# 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

Configure MCP service on the platform

Step 1: Create a custom MCP service

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.

Step 2: Configure a data center and get authentication information

Add a data center on the service details page, and get the client_id and client_secret for SDK initialization.

Step 3: Verify service connection

After the service starts, open the service details page and verify that the connection status is Connected.

Debug tools

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.

Integrate a knowledge base (RAG)

Overview

A recipe knowledge base supplies domain knowledge to the agent via RAG, improving recommendation quality and accuracy.

Knowledge base guidelines

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.

Knowledge base lifecycle

Create → Edit (Draft) → Publish → Maintain and update
                         ↓
                   Bind to the agent

The platform supports state management (published, draft, and unpublished), content search, and filtering.

AI agent orchestration

Configure skills

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.

Multi-tool call example

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.

Prompt engineering

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.

Technical highlights

Tuya MCP SDK features

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.

Benefits of multi-tool orchestration

Multi-tool orchestration enables the agent to combine information from multiple tools and services automatically.

  • Context integration: Uses the output of one tool as the input to another, enabling seamless data flow across multiple services.
  • Dynamic tool selection: Selects and calls tools based on user intent without hard-coded workflows.
  • Extensibility: New MCP services can be integrated through platform configuration without modifying the agent logic.

Best practices

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.