### Install MCP Servers (Bash) Source: https://github.com/xspoonai/spoon-core/blob/main/examples/README.md Installs Tavily for web search and GitHub integration via npm. Requires Node.js and npm to be installed. ```bash npm install -g tavily-mcp npm install -g @modelcontextprotocol/server-github ``` -------------------------------- ### Install Spoon Core from Source using uv (Bash) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/installation.md This snippet demonstrates installing the Spoon Core framework from source using 'uv', a faster alternative to pip. It includes cloning the repository, installing dependencies, and then installing the package, similar to the pip method but leveraging uv for potentially faster operations. ```bash # Clone the repo git clone https://github.com/XSpoonAi/spoon-core.git cd spoon-core # Install using uv uv pip install -r requirements.txt uv pip install -e . ``` -------------------------------- ### Run x402 Agent Demo (Bash) Source: https://github.com/xspoonai/spoon-core/blob/main/examples/README.md Executes the Python script `x402_agent_demo.py` using `uv run`. This script showcases x402 payment setup, header signing, and agent tooling. ```bash uv run python examples/x402_agent_demo.py ``` -------------------------------- ### Install Spoon Core from Source using pip (Bash) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/installation.md This snippet shows how to install the Spoon Core framework from its source code repository. It involves cloning the repository, installing dependencies from 'requirements.txt', and then installing the package itself, optionally in editable mode. ```bash # Clone the repository git clone https://github.com/XSpoonAi/spoon-core.git cd spoon-core # Install dependencies pip install -r requirements.txt # Optional: install in editable mode pip install -e . ``` -------------------------------- ### Copy Example .env File (Bash) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Command to copy the example .env file to a new .env file in the project root. This is the first step in setting up your SpoonOS configuration using environment variables, allowing you to then edit the new .env file with your specific credentials. ```bash cp .env.example .env ``` -------------------------------- ### Configure SSE MCP Tool Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Example configuration for an SSE MCP tool. This setup requires a manually started SSE server and specifies the endpoint URL, transport type, and connection timeouts. ```json { "name": "my_custom_tool", "type": "mcp", "mcp_server": { "endpoint": "http://127.0.0.1:8765/sse", "transport": "sse", "timeout": 30, "retry_attempts": 3 } } ``` -------------------------------- ### Install Spoon-AI-SDK using pip (Python) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/installation.md This code installs the Spoon-AI-SDK package directly from the Python Package Index (PyPI) using the pip package manager. It's a straightforward method for getting the latest stable release. ```python pip install spoon-ai-sdk ``` -------------------------------- ### Run Turnkey Trading Use Case (Python) Source: https://github.com/xspoonai/spoon-core/blob/main/examples/README.md Executes a guided demo for Turnkey's trading use case, including transaction signing, optional broadcasting, message signing, EIP-712, and audit. ```python python -m examples.turnkey.turnkey_trading_use_case ``` -------------------------------- ### Copy Turnkey Environment Example (Bash) Source: https://github.com/xspoonai/spoon-core/blob/main/examples/README.md Copies the example environment file for Turnkey integration to `.env`. Users should then fill in the required values in the `.env` file. ```bash cp examples/turnkey/env.example .env ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md A sample .env file showing common environment variables for SpoonOS, including API keys for LLM providers (OpenAI, Anthropic, Deepseek), blockchain credentials, and tool-specific keys (Tavily, Brave, GitHub). Also includes variables for specific tools like OKX, Chainbase, Thirdweb, and Turnkey. ```dotenv # LLM APIs OPENAI_API_KEY=sk-your-openai-key ANTHROPIC_API_KEY=sk-your-anthropic-key DEEPSEEK_API_KEY=your-deepseek-key # Blockchain PRIVATE_KEY=your-wallet-private-key RPC_URL=https://mainnet.rpc CHAIN_ID=12345 # Tool-specific environment variables TAVILY_API_KEY=your-tavily-api-key BRAVE_API_KEY=your-brave-search-key GITHUB_TOKEN=your-github-token # Built-in tool environment variables OKX_API_KEY=your_okx_api_key OKX_SECRET_KEY=your_okx_secret_key OKX_API_PASSPHRASE=your_okx_api_passphrase OKX_PROJECT_ID=your_okx_project_id CHAINBASE_API_KEY=your_chainbase_api_key THIRDWEB_CLIENT_ID=your_thirdweb_client_id BITQUERY_API_KEY=your_bitquery_api_key # Turnkey SDK - Required for spoon_ai.turnkey.Turnkey client TURNKEY_BASE_URL=https://api.turnkey.com TURNKEY_API_PUBLIC_KEY=your_turnkey_public_key_here TURNKEY_API_PRIVATE_KEY=your_turnkey_private_key_hex_here TURNKEY_ORG_ID=your_turnkey_organization_id_here ``` -------------------------------- ### Add New Tools to MCP Service Setup Source: https://github.com/xspoonai/spoon-core/blob/main/spoon_ai/tools/README_MCP_TOOLS.md Provides an example of how to extend the MCP service by adding new tools to the `_setup_tools` method. This is the standard way to integrate additional functionalities. ```python def _setup_tools(self): self.add_tool(PredictPriceTool()) self.add_tool(TokenHoldersTool()) self.add_tool(YourNewAwesomeTool()) # Add your new tool here! ``` -------------------------------- ### Create and Activate Virtual Environment (Bash/Batch) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/installation.md This snippet demonstrates how to create and activate a Python virtual environment using the 'venv' module. It provides commands for both macOS/Linux and Windows operating systems to isolate project dependencies. ```bash # Create and activate a virtual environment (macOS/Linux) python -m venv spoon-env source spoon-env/bin/activate ``` ```batch # For Windows python -m venv spoon-env spoon-env\Scripts\activate ``` -------------------------------- ### Production-Ready MCP Tool Configuration Example Source: https://github.com/xspoonai/spoon-core/blob/main/doc/agent.md Illustrates how to configure MCP tools for production use in Python. It emphasizes environment variable validation for API keys (TAVILY_API_KEY, GITHUB_TOKEN, OKX_API_KEY), using the stdio transport, and setting timeouts and retry attempts for reliability. Includes error handling for tool initialization. ```python async def initialize(self): """Initialize agent with production-ready tool configuration""" # Validate required environment variables required_env_vars = ["TAVILY_API_KEY", "GITHUB_TOKEN", "OKX_API_KEY"] for var in required_env_vars: if not os.getenv(var): raise ValueError(f"Required environment variable {var} is not set") # Configure tools with proper error handling tools = [] # Stdio-based tools (recommended) try: tavily_tool = MCPTool( name="tavily-search", description="Web search using Tavily API", mcp_config={ "command": "npx", "args": ["-y", "tavily-mcp"], "env": {"TAVILY_API_KEY": os.getenv("TAVILY_API_KEY")}, "transport": "stdio", "timeout": 30, "retry_attempts": 3 } ) tools.append(tavily_tool) except Exception as e: logging.warning(f"Failed to initialize Tavily tool: {e}") # Built-in tools try: crypto_tool = CryptoPowerDataCEXTool() tools.append(crypto_tool) except Exception as e: logging.warning(f"Failed to initialize crypto tool: {e}") self.avaliable_tools = ToolManager(tools) logging.info(f"Initialized {len(tools)} tools successfully") ``` -------------------------------- ### Start GitHub MCP Server as SSE (Bash) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Bash command to start the GitHub MCP server specifically configured to run as a Server-Sent Events (SSE) server. The `--sse` flag enables this mode. ```bash # Example: GitHub MCP server as SSE npx -y @modelcontextprotocol/server-github --sse ``` -------------------------------- ### Intelligent Trade Bot Usage Example Source: https://github.com/xspoonai/spoon-core/blob/main/doc/graph_agent.md An asynchronous example demonstrating how to instantiate and use the IntelligentTradeBot. It defines a list of sample queries and iterates through them, printing the trade decision and confidence score for each. ```python # Usage example async def main(): bot = IntelligentTradeBot() queries = [ "What's the current price of BTC?", "Should I buy Ethereum right now?", "Execute a buy order for 0.1 BTC" ] for query in queries: result = await bot.process_query(query) print(f"Result: {result.get('trade_decision', 'No decision')}") print(f"Confidence: {result.get('confidence_score', 0):.1%}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize Trading Agent with Crypto Tools in Python Source: https://github.com/xspoonai/spoon-core/blob/main/doc/builtin_tools.md Python code example demonstrating how to initialize a SpoonReactAI trading agent and integrate it with specific crypto tools like CryptoPowerDataCEXTool and GetTokenPriceTool. It shows the instantiation of tools with their parameters and then passing them to the agent's constructor. ```python import os from spoon_ai.agents import SpoonReactAI from spoon_toolkits.crypto.crypto_powerdata.tools import CryptoPowerDataCEXTool from spoon_toolkits.crypto.crypto_data_tools.price_data import GetTokenPriceTool # Initialize tools crypto_tool = CryptoPowerDataCEXTool( exchange="binance", symbol="BTC/USDT", timeframe="1h", limit=100 ) price_tool = GetTokenPriceTool( exchange="uniswap" ) # Create agent with tools trading_agent = SpoonReactAI( name="trading_agent", tools=[crypto_tool, price_tool], config={ "max_steps": 10, "temperature": 0.3 } ) # Use agent response = await trading_agent.run("Analyze BTC market data") ``` -------------------------------- ### Troubleshoot Tool Loading Failures in Python Source: https://github.com/xspoonai/spoon-core/blob/main/doc/builtin_tools.md Provides commands to troubleshoot tool loading failures. This involves checking the Python path to ensure modules are discoverable and verifying that all project dependencies are installed using `pip install -r requirements.txt`. ```bash # Check Python path python -c "import spoon_toolkits.crypto.crypto_powerdata" # Verify dependencies pip install -r requirements.txt ``` -------------------------------- ### Run Turnkey Multi-Account Use Case (Python) Source: https://github.com/xspoonai/spoon-core/blob/main/examples/README.md Executes a demo for Turnkey's multi-account capabilities, including enumerating wallets, per-account transaction signing, optional broadcasting, message signing, and audit. ```python python -m examples.turnkey.multi_account_use_case ``` -------------------------------- ### Create Basic Graph with State Management and Monitoring Source: https://github.com/xspoonai/spoon-core/blob/main/doc/graph_agent.md Demonstrates how to create a basic StateGraph workflow with state schema definition, node functions, edges, and execution metrics. This example shows fundamental workflow orchestration including input processing, result generation, and monitoring setup. ```python from spoon_ai.graph import StateGraph, NodeContext, NodeResult from datetime import datetime # Define your state schema class WorkflowState: input_text: str = "" processed_text: str = "" final_result: str = "" confidence: float = 0.0 timestamp: str = "" # Create the graph graph = StateGraph(WorkflowState) # Enable monitoring and cleanup graph.enable_monitoring(["execution_time", "success_rate", "node_performance"]) graph.set_default_state_cleanup() # Define node functions async def process_input(state, context: NodeContext): """Process the input text""" processed = state["input_text"].upper() return NodeResult( updates={ "processed_text": processed, "timestamp": datetime.now().isoformat() }, confidence=0.9, metadata={"processing_method": "uppercase"} ) async def generate_result(state, context: NodeContext): """Generate the final result""" result = f"Result: {state['processed_text']} (processed at {state['timestamp']})" return NodeResult( updates={"final_result": result}, confidence=0.95 ) # Add nodes to graph graph.add_node("process", process_input) graph.add_node("generate", generate_result) # Add edges graph.add_edge("process", "generate") graph.set_entry_point("process") # Compile and execute compiled = graph.compile() result = await compiled.invoke({"input_text": "hello world"}) print(f"Final result: {result['final_result']}") print(f"Confidence: {result.get('confidence', 0):.1%}") # Get execution metrics metrics = compiled.get_execution_metrics() print(f"Total executions: {metrics['total_executions']}") print(f"Success rate: {metrics['success_rate']:.1%}") ``` -------------------------------- ### Configure Stdio MCP Tool for Tavily Search Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Example configuration for a Stdio MCP tool, specifically for Tavily Search. It specifies the command to execute, arguments, transport type, environment variables, and retry settings. ```json { "name": "tavily_search", "type": "mcp", "mcp_server": { "command": "npx", "args": ["-y", "tavily-mcp"], "transport": "stdio", "env": { "TAVILY_API_KEY": "your-tavily-api-key" }, "timeout": 30, "retry_attempts": 3 } } ``` -------------------------------- ### Agent Definition Example (JSON) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md This JSON snippet illustrates the structure for defining a custom agent within the Spoon Core configuration. It includes parameters like class, aliases, description, and specific configurations. ```json "agents": { "custom_react": { "class": "SpoonReactAI", "aliases": ["custom", "my_react"], "description": "Custom configured SpoonReact agent", "config": { "max_steps": 15, "tool_choice": "auto", "llm_provider": "openai" } } } ``` -------------------------------- ### Install and Run MCP Tools Server Source: https://github.com/xspoonai/spoon-core/blob/main/spoon_ai/tools/README_MCP_TOOLS.md Installs the FastMCP library and runs the MCP tools server for SpoonOS. This is the initial step to make SpoonOS tools available as MCP services. ```bash # Install FastMCP pip install fastmcp # Run the MCP tools server python -m spoon_ai.tools.mcp_tools_collection ``` -------------------------------- ### Python: Basic Memory System Usage Source: https://github.com/xspoonai/spoon-core/blob/main/doc/graph_agent.md Provides a basic example of initializing and using the Memory class from Spoon AI. It demonstrates importing the necessary components and creating a Memory instance. This serves as a starting point for integrating persistent memory into applications. ```python from spoon_ai.graph import GraphAgent, Memory ``` -------------------------------- ### Basic Provider Usage in Python Source: https://github.com/xspoonai/spoon-core/blob/main/spoon_ai/llm/README.md Demonstrates how to get and use a provider (e.g., OpenAI) from the global registry. It shows initialization and making a chat request. Requires the 'spoon-ai' library and an initialized registry with configured providers. ```python from spoon_ai.llm import get_global_registry from spoon_ai.schema import Message # Get a provider (assumes it's already registered and configured) registry = get_global_registry() provider = registry.get_provider("openai", { "api_key": "your-api-key", "model": "gpt-4" }) # Initialize and use await provider.initialize(config) response = await provider.chat([ Message(role="user", content="Hello, world!") ]) print(response.content) ``` -------------------------------- ### GitHub MCP Server Configuration (JSON) Source: https://github.com/xspoonai/spoon-core/blob/main/examples/README.md Configures the GitHub MCP server, specifying the command to run, arguments, and environment variables including the personal access token. ```json { "github-mcp": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "your-token" } } } ``` -------------------------------- ### List Available Agents (CLI) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Demonstrates the command-line interface command to list all available agents and their aliases, as well as currently loaded agents within the SpoonOS system. ```bash > list-agents Available agents: react (aliases: spoon_react): A smart ai agent in neo blockchain spoon_react (aliases: react): A smart ai agent in neo blockchain spoon_react_mcp: SpoonReact agent with MCP support custom_react (aliases: custom, my_react): Custom configured SpoonReact agent search_agent (aliases: search, tavily): Search agent with Tavily MCP integration Currently loaded agents: spoon_react: A smart ai agent in neo blockchain ``` -------------------------------- ### Full Refactored Spoon Macro Analysis Agent Example Source: https://github.com/xspoonai/spoon-core/blob/main/doc/agent.md Demonstrates a complete, refactored Python script for the Spoon Macro Analysis Agent. It showcases a transport-agnostic approach, agent initialization with API keys, tool loading (Tavily search and CryptoPowerDataCEXTool), and running a macro analysis query. Requires TAVILY_API_KEY environment variable. ```python import os import sys import asyncio import logging from typing import Dict, Any sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../spoon-toolkit'))) from spoon_ai.agents.spoon_react_mcp import SpoonReactMCP from spoon_ai.tools.mcp_tool import MCPTool from spoon_ai.tools.tool_manager import ToolManager from spoon_ai.chat import ChatBot from spoon_toolkits.crypto.crypto_powerdata.tools import CryptoPowerDataCEXTool logging.basicConfig(level=logging.INFO) class SpoonMacroAnalysisAgent(SpoonReactMCP): name: str = "SpoonMacroAnalysisAgent" system_prompt: str = ( '''You are a cryptocurrency market analyst. Your task is to provide a comprehensive macroeconomic analysis of a given token...''' ) def __init__(self, **kwargs): super().__init__(**kwargs) self.avaliable_tools = ToolManager([]) async def initialize(self): logging.info("Initializing agent and loading tools...") tavily_key = os.getenv("TAVILY_API_KEY", "") if not tavily_key or "your-tavily-api-key-here" in tavily_key: raise ValueError("TAVILY_API_KEY is not set or is a placeholder.") tavily_tool = MCPTool( name="tavily-search", description="Performs a web search using the Tavily API.", mcp_config={ "command": "npx", "args": ["--yes", "tavily-mcp"], "env": {"TAVILY_API_KEY": tavily_key} } ) crypto_tool = CryptoPowerDataCEXTool() self.avaliable_tools = ToolManager([tavily_tool, crypto_tool]) logging.info(f"Available tools: {list(self.avaliable_tools.tool_map.keys())}") async def main(): print("--- SpoonOS Macro Analysis Agent Demo ---") agent = SpoonMacroAnalysisAgent(llm=ChatBot(llm_provider="openai")) print("Agent instance created.") await agent.initialize() query = "Perform a macro analysis of the NEO token." print(f"\nRunning query: {query}") response = await agent.run(query) print(f"\n--- Analysis Complete ---\n{response}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Configure Multiple Stdio MCP Tools Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Demonstrates how to configure a list of Stdio MCP tools, including Tavily Search, GitHub tools, and Brave Search. Each tool is defined with its specific command and arguments for execution via npx. ```json { "tools": [ { "name": "tavily_search", "type": "mcp", "mcp_server": { "command": "npx", "args": ["-y", "tavily-mcp"], "transport": "stdio" } }, { "name": "github_tools", "type": "mcp", "mcp_server": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "transport": "stdio" } }, { "name": "brave_search", "type": "mcp", "mcp_server": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "transport": "stdio" } } ] } ``` -------------------------------- ### View Current System Configuration (CLI) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Command to display the current configuration settings, including API keys for different providers, base URL, default agent, and other agent-related configurations. ```bash > config Current configuration: API Keys: openai: sk-o...xxxx anthropic: Not set deepseek: Not set base_url: https://openrouter.ai/api/v1 default_agent: spoon_react agents: [object Object] ``` -------------------------------- ### Environment Variables (.env file) Source: https://github.com/xspoonai/spoon-core/blob/main/README.md Configure SpoonOS by setting environment variables in a `.env` file. This is the recommended method for initial setup. ```APIDOC ## Environment Variables (.env file) ### Description Configure SpoonOS by setting environment variables in a `.env` file. This is the recommended method for initial setup. ### Method Environment Variables ### Endpoint N/A ### Parameters #### Environment Variables - **OPENAI_API_KEY** (string) - Required - Your OpenAI API key. - **ANTHROPIC_API_KEY** (string) - Required - Your Anthropic API key. - **DEEPSEEK_API_KEY** (string) - Required - Your DeepSeek API key. - **GEMINI_API_KEY** (string) - Required - Your Gemini API key. - **PRIVATE_KEY** (string) - Required - Your Web3 wallet private key. - **RPC_URL** (string) - Required - The RPC URL for your blockchain. - **CHAIN_ID** (string) - Required - The ID of your blockchain. - **TURNKEY_BASE_URL** (string) - Required - Base URL for Turnkey SDK. - **TURNKEY_API_PUBLIC_KEY** (string) - Required - Public key for Turnkey API. - **TURNKEY_API_PRIVATE_KEY** (string) - Required - Private key (hex) for Turnkey API. - **TURNKEY_ORG_ID** (string) - Required - Your Turnkey organization ID. - **TAVILY_API_KEY** (string) - Required - Your Tavily API key. - **OKX_API_KEY** (string) - Required - Your OKX API key. - **OKX_SECRET_KEY** (string) - Required - Your OKX secret key. - **OKX_API_PASSPHRASE** (string) - Required - Your OKX API passphrase. ### Request Example ```bash # LLM Provider Keys OPENAI_API_KEY=sk-your-openai-key ANTHROPIC_API_KEY=sk-your-claude-key DEEPSEEK_API_KEY=your-deepseek-key GEMINI_API_KEY=your-gemini-api-key # Web3 Configuration PRIVATE_KEY=your-wallet-private-key RPC_URL=https://mainnet.rpc CHAIN_ID=12345 # Turnkey SDK Configuration TURNKEY_BASE_URL=https://api.turnkey.com TURNKEY_API_PUBLIC_KEY=your-turnkey-public-key TURNKEY_API_PRIVATE_KEY=your-turnkey-private-key-hex TURNKEY_ORG_ID=your-turnkey-organization-id # Tool-specific Keys TAVILY_API_KEY=your-tavily-api-key OKX_API_KEY=your-okx-api-key OKX_SECRET_KEY=your-okx-secret-key OKX_API_PASSPHRASE=your-okx-passphrase ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Set Environment Variables (Bash) Source: https://github.com/xspoonai/spoon-core/blob/main/examples/README.md Sets API keys for Tavily and GitHub as environment variables. These are necessary for the respective MCP servers to function. ```bash export TAVILY_API_KEY="your-tavily-api-key" export GITHUB_PERSONAL_ACCESS_TOKEN="your-github-token" ``` -------------------------------- ### Complete Spoon Core Configuration Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md This JSON object demonstrates a comprehensive configuration for Spoon Core, including API keys, LLM provider settings, agent definitions, and tool configurations for web search and crypto data. ```json { "api_keys": { "openai": "sk-your-openai-api-key", "anthropic": "sk-ant-your-anthropic-api-key", "deepseek": "your-deepseek-api-key" }, "default_agent": "web_researcher", "providers": { "openai": { "api_key": "sk-your-openai-key", "model": "gpt-4.1", "max_tokens": 4096, "temperature": 0.3, "timeout": 30, "retry_attempts": 3 }, "anthropic": { "api_key": "sk-ant-your-key", "model": "claude-3-5-sonnet-20241022", "max_tokens": 4096, "temperature": 0.3, "timeout": 30, "retry_attempts": 3 } }, "llm_settings": { "default_provider": "openai", "fallback_chain": ["openai", "anthropic"], "enable_monitoring": true, "enable_caching": true, "enable_debug_logging": false, "max_concurrent_requests": 10 }, "agents": { "web_researcher": { "class": "SpoonReactMCP", "description": "Agent with web search and analysis capabilities", "aliases": ["researcher", "web"], "config": { "max_steps": 10, "tool_choice": "auto" }, "tools": [ { "name": "web_search", "type": "mcp", "description": "Web search via Tavily API", "enabled": true, "mcp_server": { "command": "npx", "args": ["-y", "@tavily/mcp-server"], "env": { "TAVILY_API_KEY": "your-tavily-api-key" }, "disabled": false, "autoApprove": ["search", "get_content"], "timeout": 30, "retry_attempts": 3 }, "config": { "max_results": 10, "include_raw_content": true } }, { "name": "crypto_powerdata_cex", "type": "builtin", "description": "Crypto PowerData CEX market data tool", "enabled": true, "env": { "OKX_API_KEY": "your_okx_api_key", "OKX_SECRET_KEY": "your_okx_secret_key", "OKX_API_PASSPHRASE": "your_okx_api_passphrase", "OKX_PROJECT_ID": "your_okx_project_id" }, "config": { "timeout": 30, "max_retries": 3 } } ] } } } ``` -------------------------------- ### Load Agent by Name or Alias (CLI) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Shows how to load an agent using its name or one of its aliases via the command line. The output confirms the agent that has been successfully loaded. ```bash > load-agent search_agent Loaded agent: spoon_react > load-agent search Loaded agent: spoon_react ``` -------------------------------- ### Build Unsigned EIP-1559 Transaction (Python) Source: https://github.com/xspoonai/spoon-core/blob/main/examples/README.md Builds a minimal unsigned EIP-1559 transaction and prints the `TURNKEY_UNSIGNED_TX_HEX`. This is a prerequisite for certain Turnkey operations. ```python python -m examples.turnkey.build_unsigned_eip1559_tx ``` -------------------------------- ### Start New Chat Session Source: https://github.com/xspoonai/spoon-core/blob/main/doc/cli.md Initiates a new chat session with the AI agent. Resets conversation context and prepares the agent for fresh interaction. ```bash > action chat New chat session started ``` -------------------------------- ### Deploy x402 FastAPI Gateway for Paywalled Agents Source: https://github.com/xspoonai/spoon-core/blob/main/README.md Start the FastAPI payment gateway that protects agent invocations with x402 payment verification. The gateway exposes endpoints for discovering payment requirements, invoking agents with payment verification, and returning settlement receipts in response headers. ```bash uv run python -m spoon_ai.payments.app ``` -------------------------------- ### Tavily MCP Server Configuration (JSON) Source: https://github.com/xspoonai/spoon-core/blob/main/examples/README.md Configures the Tavily MCP server, specifying the command to run, arguments, and environment variables including the API key. ```json { "tavily-mcp": { "command": "npx", "args": ["-y", "tavily-mcp"], "env": { "TAVILY_API_KEY": "your-api-key" } } } ``` -------------------------------- ### Error Handling for Nonexistent Agent (CLI) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Illustrates the system's behavior when attempting to load an agent that does not exist. It displays an error message and lists all available agents. ```bash > load-agent nonexistent Agent nonexistent not found Available agents: react (aliases: spoon_react): A smart ai agent in neo blockchain search_agent (aliases: search, tavily): Search agent with Tavily MCP integration ``` -------------------------------- ### Configure .env File with API Keys and Web3 Credentials Source: https://github.com/xspoonai/spoon-core/blob/main/README.md Populate the .env file with all required credentials including LLM provider keys, Web3 wallet configuration, Turnkey SDK settings, and third-party service API keys. This file serves as the foundation for SpoonOS initialization. ```bash # LLM Provider Keys OPENAI_API_KEY=sk-your-openai-key ANTHROPIC_API_KEY=sk-your-claude-key DEEPSEEK_API_KEY=your-deepseek-key GEMINI_API_KEY=your-gemini-api-key # Web3 Configuration PRIVATE_KEY=your-wallet-private-key RPC_URL=https://mainnet.rpc CHAIN_ID=12345 # Turnkey SDK Configuration TURNKEY_BASE_URL=https://api.turnkey.com TURNKEY_API_PUBLIC_KEY=your-turnkey-public-key TURNKEY_API_PRIVATE_KEY=your-turnkey-private-key-hex TURNKEY_ORG_ID=your-turnkey-organization-id # Tool-specific Keys TAVILY_API_KEY=your-tavily-api-key OKX_API_KEY=your-okx-api-key OKX_SECRET_KEY=your-okx-secret-key OKX_API_PASSPHRASE=your-okx-passphrase ``` -------------------------------- ### Check Available Tools in Python Source: https://github.com/xspoonai/spoon-core/blob/main/doc/agent.md This Python code snippet shows how to retrieve and print a list of available tools managed by the `ToolManager`. It accesses the `tool_map` attribute to get the keys, representing the names of the available tools. ```python print(f"Available tools: {list(self.avaliable_tools.tool_map.keys())}") ``` -------------------------------- ### Environment Variable Priority Configuration Example Source: https://github.com/xspoonai/spoon-core/blob/main/doc/builtin_tools.md Illustrates the priority order for environment variables in SpoonOS configurations. It shows how tool-level environment variables take precedence over system environment variables, which in turn override API keys defined in configuration files. ```python # 1. Tool-level env vars (highest priority) { "tools": [{ "env": { "OKX_API_KEY": "${TOOL_SPECIFIC_OKX_KEY}" } }] } # 2. System environment variables export OKX_API_KEY="your-system-api-key" # 3. Configuration file API keys (lowest priority) { "api_keys": { "okx": "${CONFIG_OKX_KEY}" } } ``` -------------------------------- ### Interact with Configured Spoon Agents Source: https://github.com/xspoonai/spoon-core/blob/main/doc/cli.md Demonstrates how to use a configured agent, like the DeepWiki agent, via the command line. This involves loading the agent and then issuing natural language queries to it for repository analysis. ```bash # Load the DeepWiki agent > load-agent deepwiki_agent # Ask about XSpoonAi/spoon-core repository > Can you analyze the XSpoonAi/spoon-core repository and tell me what this project does? # Ask about React repository > What are the main documentation topics available for facebook/react? ``` -------------------------------- ### Install SpoonAI Tools for Claude Desktop Source: https://github.com/xspoonai/spoon-core/blob/main/spoon_ai/tools/README_MCP_TOOLS.md Installs the SpoonAI tools collection for use with Claude Desktop. This command registers the specified Python file as an MCP service with a given name. ```bash fastmcp install spoon_ai/tools/mcp_tools_collection.py --name "SpoonAI Tools" ``` -------------------------------- ### Define SpoonMacroAnalysisAgent Class in Python Source: https://github.com/xspoonai/spoon-core/blob/main/doc/agent.md Defines a custom agent class by inheriting from SpoonReactMCP. It sets the agent's name, system prompt which guides its behavior, and initializes an empty ToolManager. This establishes the agent's identity and its foundational reasoning instructions. ```python class SpoonMacroAnalysisAgent(SpoonReactMCP): name: str = "SpoonMacroAnalysisAgent" system_prompt: str = ( '''You are a cryptocurrency market analyst. Your task is to provide a comprehensive macroeconomic analysis of a given token. To do this, you will perform the following steps: 1. Use the `crypto_power_data_cex` tool to get the latest candlestick data and technical indicators. 2. Use the `tavily-search` tool to find the latest news and market sentiment. 3. Synthesize the data from both tools to form a holistic analysis.''' ) def __init__(self, **kwargs): super().__init__(**kwargs) self.avaliable_tools = ToolManager([]) ``` -------------------------------- ### Configure x402 Payment System Credentials Source: https://github.com/xspoonai/spoon-core/blob/main/README.md Set up x402 payment integration by adding wallet private key, receiver address, facilitator URL, default asset (USDC), network, and payment amount to the .env file. These credentials enable agents to pay for external services and expose paywalled endpoints. ```bash X402_AGENT_PRIVATE_KEY=0xyour-agent-wallet-private-key X402_RECEIVER_ADDRESS=0xwallet-that-receives-fees X402_FACILITATOR_URL=https://x402.org/facilitator X402_DEFAULT_ASSET=0xa063B8d5ada3bE64A24Df594F96aB75F0fb78160 X402_DEFAULT_NETWORK=base-sepolia X402_DEFAULT_AMOUNT_USDC=0.10 ``` -------------------------------- ### Configuration Management in Python Source: https://github.com/xspoonai/spoon-core/blob/main/spoon_ai/llm/README.md Demonstrates using the `ConfigurationManager` to load provider-specific configurations and retrieve the default provider. It prioritizes environment variables over file-based configurations. ```python from spoon_ai.llm import ConfigurationManager config_manager = ConfigurationManager() # environment-first configuration # Load provider configuration provider_config = config_manager.load_provider_config("openai") print(f"Model: {provider_config.model}") print(f"Max tokens: {provider_config.max_tokens}") # Get default provider default = config_manager.get_default_provider() ``` -------------------------------- ### Validate Configuration File with Python Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md A Python command-line script to validate the syntax of the `config.json` file, checking if it's valid JSON. ```bash python -c "import json; print('Valid JSON' if json.load(open('config.json')) else 'Invalid JSON')" > config validate ``` -------------------------------- ### Configure MCP Tools for Runtime Discovery with SpoonReactMCP Source: https://context7.com/xspoonai/spoon-core/llms.txt Demonstrates how to dynamically load and configure multiple MCP (Model Context Protocol) tools including Tavily search, GitHub access, and HTTP-based blockchain API servers. The agent initializes with these tools and can execute queries that utilize multiple MCP sources. Tools are configured via command-based (npx) or HTTP transport with environment variables and timeout settings. ```python import asyncio import os from spoon_ai.agents import SpoonReactMCP from spoon_ai.tools.mcp_tool import MCPTool from spoon_ai.chat import ChatBot async def mcp_agent_demo(): # Configure Tavily search tool via MCP tavily_tool = MCPTool( name="tavily-search", description="Search the web for current information using Tavily API", mcp_config={ "command": "npx", "args": ["--yes", "tavily-mcp"], "env": {"TAVILY_API_KEY": os.getenv("TAVILY_API_KEY")}, "timeout": 30, "max_retries": 3 } ) # Configure GitHub MCP tool github_tool = MCPTool( name="github", description="Access GitHub repositories, issues, and pull requests", mcp_config={ "command": "npx", "args": ["--yes", "@modelcontextprotocol/server-github"], "env": {"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")} } ) # Configure HTTP-based MCP server api_tool = MCPTool( name="blockchain-api", description="Access blockchain data via HTTP MCP server", mcp_config={ "url": "https://mcp-server.example.com/api", "transport": "http", "headers": {"Authorization": f"Bearer {os.getenv('API_TOKEN')}"}, "timeout": 60 } ) # Create agent with MCP tools agent = SpoonReactMCP( llm=ChatBot(llm_provider="openai", model_name="gpt-4.1"), tools=[tavily_tool, github_tool, api_tool], system_prompt=""" You are a research assistant with access to: 1. tavily-search - for web research 2. github - for code repository analysis 3. blockchain-api - for on-chain data Use tools strategically to provide comprehensive answers. """, max_steps=15 ) await agent.initialize() # Query that uses multiple MCP tools result = await agent.run( "Research the latest developments in Ethereum Layer 2 solutions. " "Check GitHub for popular L2 projects and search for recent news." ) print(f"Research result:\n{result}") # List all available MCP tools discovered at runtime mcp_tools = await agent.list_mcp_tools() for tool in mcp_tools: print(f"Tool: {tool.name} - {tool.description}") asyncio.run(mcp_agent_demo()) ``` -------------------------------- ### Python: Integrating Turnkey with x402 Payments Source: https://context7.com/xspoonai/spoon-core/llms.txt Shows how to configure and use the X402PaymentService in Python, with Turnkey as the signing mechanism. It requires specific environment variables to link Turnkey to the x402 service. The service automatically handles payment requirement building and header creation, with signatures generated via the Turnkey API. ```python import os from spoon_ai.payments import X402PaymentService # Configure Turnkey for x402 (in .env file) """ X402_CLIENT_USE_TURNKEY=true X402_TURNKEY_SIGN_WITH=0x_your_wallet_address X402_TURNKEY_ADDRESS=0x_your_wallet_address TURNKEY_API_PUBLIC_KEY=... TURNKEY_API_PRIVATE_KEY=... TURNKEY_ORG_ID=... """ # Service automatically uses Turnkey for signing service = X402PaymentService() # All payment operations now use Turnkey requirements = service.build_payment_requirements() payment_header = service.build_payment_header(requirements) # Payment signatures are created via Turnkey API print(f"Payment header (Turnkey-signed): {payment_header}") ``` -------------------------------- ### Modify Default Agent Configuration (CLI) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Demonstrates how to change the default agent using the configuration command, specifying the new default agent name. ```bash > config default_agent search_agent Set default_agent = search_agent ``` -------------------------------- ### x402 Command-line Helpers Source: https://github.com/xspoonai/spoon-core/blob/main/README.md Utilize bundled CLI helpers for x402 payment operations. ```APIDOC ## x402 Command-line Helpers ### Description Use the bundled CLI to inspect requirements, sign headers, or verify incoming x402 requests. ### Method CLI Commands ### Endpoint N/A ### Commands - **`uv run python -m spoon_ai.payments.cli requirements`**: Inspect x402 payment requirements. - **`uv run python -m spoon_ai.payments.cli sign --amount-usdc --resource `**: Sign x402 payment headers. - **`uv run python -m spoon_ai.payments.cli verify `**: Verify incoming x402 headers. ### Request Example ```bash # Inspect requirements uv run python -m spoon_ai.payments.cli requirements # Sign a payment header uv run python -m spoon_ai.payments.cli sign --amount-usdc 0.05 --resource https://api.example.com/data # Verify an incoming header uv run python -m spoon_ai.payments.cli verify ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Protected Data Access Source: https://context7.com/xspoonai/spoon-core/llms.txt An example endpoint demonstrating protected data access that requires payment verification via the 'X-PAYMENT' header. ```APIDOC ## GET /protected/data ### Description Example protected endpoint that requires payment verification. ### Method GET ### Endpoint /protected/data ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **data** (string) - The protected content. - **status** (string) - Payment status. #### Response Example ```json { "data": "Premium content here", "status": "paid" } ``` #### Error Responses - **402 Payment Required**: If 'X-PAYMENT' header is missing or invalid. ``` -------------------------------- ### Enable Debug Logging in LLM Settings Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md A JSON snippet showing how to enable debug logging for LLM operations by setting the `enable_debug_logging` option within `llm_settings` to true. ```json { "llm_settings": { "enable_debug_logging": true } } ``` -------------------------------- ### Initialize Agent Instances Source: https://context7.com/xspoonai/spoon-core/llms.txt This snippet demonstrates the initialization of agent instances for 'trading_agent' and 'research_agent'. It utilizes SpoonReactAI and ChatBot, specifying different LLM providers (OpenAI and Anthropic) for each agent. This setup is crucial for managing and differentiating agent functionalities within the application. ```python agents = { "trading_agent": SpoonReactAI(llm=ChatBot(llm_provider="openai")), "research_agent": SpoonReactAI(llm=ChatBot(llm_provider="anthropic")) } ``` -------------------------------- ### Run MCP Tools in Development Mode Source: https://github.com/xspoonai/spoon-core/blob/main/spoon_ai/tools/README_MCP_TOOLS.md Starts the MCP tools server in development mode, allowing for interactive testing of your SpoonOS tools. This is useful for debugging and rapid development. ```bash fastmcp dev spoon_ai/tools/mcp_tools_collection.py ``` -------------------------------- ### Agent Configuration Schema Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Defines the schema for configuring individual agents, including specifying the class, description, aliases, and internal configuration options like max steps and tool choice. ```json { "agent_name": { "class": "SpoonReactAI | SpoonReactMCP", "description": "string (optional)", "aliases": ["array", "of", "strings"] (optional), "config": { "max_steps": "integer (default: 10)", "tool_choice": "string (default: 'auto')" }, "tools": [ // Array of tool configurations (see below) ] } } ``` -------------------------------- ### Combine Stdio, SSE, and Built-in Tools in an Agent Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Illustrates a mixed agent configuration combining Stdio MCP (Tavily Search), SSE MCP (custom tool), and a Built-in tool (crypto_tools). This showcases how to integrate diverse tool types within a single agent definition. ```json { "agents": { "web3_agent": { "class": "SpoonReactMCP", "tools": [ { "name": "tavily_search", "type": "mcp", "mcp_server": { "command": "npx", "args": ["-y", "tavily-mcp"], "transport": "stdio", "env": { "TAVILY_API_KEY": "your-tavily-api-key" } } }, { "name": "my_custom_tool", "type": "mcp", "mcp_server": { "endpoint": "http://127.0.0.1:8765/sse", "transport": "sse" } }, { "name": "crypto_tools", "type": "builtin" } ] } } } ``` -------------------------------- ### Configure Built-in Tool in SpoonOS Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md Defines the structure for configuring a built-in tool within SpoonOS. Built-in tools are provided directly by SpoonOS and require minimal configuration, often just a name and type. ```json { "name": "string (required, unique per agent)", "type": "builtin", "description": "string (optional)", "enabled": "boolean (default: true)", "env": { "KEY": "value" } (optional), "config": { // Tool-specific configuration options } } ``` -------------------------------- ### Basic LLM Manager Usage in Python Source: https://github.com/xspoonai/spoon-core/blob/main/README.md Demonstrates fundamental usage of SpoonOS's LLMManager for interacting with language models. It covers initializing the manager, performing simple chat requests, specifying providers, and initiating chat sessions with tool capabilities. ```python import asyncio from spoon_ai.llm import LLMManager, ConfigurationManager async def main(): # Initialize the LLM manager config_manager = ConfigurationManager() llm_manager = LLMManager(config_manager) # Simple chat request (uses default provider) response = await llm_manager.chat( [{"role": "user", "content": "Hello, world!"}] ) print(response.content) # Use specific provider response = await llm_manager.chat( messages=[{"role": "user", "content": "Hello!"}], provider="anthropic", ) # Chat with tools tools = [{"name": "get_weather", "description": "Get weather info"}] response = await llm_manager.chat_with_tools( messages=[{"role": "user", "content": "What's the weather?"}], tools=tools, provider="openai", ) print(response.content) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Built-in Tool Configuration Schema (JSON) Source: https://github.com/xspoonai/spoon-core/blob/main/doc/configuration.md This JSON schema defines the configuration for a built-in tool, such as 'crypto_powerdata_cex'. It includes details on environment variables, and specific configuration parameters for the tool's operation. ```json { "name": "crypto_powerdata_cex", "type": "builtin", "description": "Crypto PowerData CEX market data", "enabled": true, "env": { "OKX_API_KEY": "your_okx_api_key", "OKX_SECRET_KEY": "your_okx_secret_key", "OKX_API_PASSPHRASE": "your_okx_api_passphrase", "OKX_PROJECT_ID": "your_okx_project_id" }, "config": { "timeout": 30, "max_retries": 3 } } ```