MCP Integration for Claude Code & Claude Desktop

Overview

This guide provides comprehensive documentation for integrating Aitana’s Model Context Protocol (MCP) servers with Claude Code and Claude Desktop. MCP enables Claude to interact with external tools and services through a standardized protocol.

Related Documentation:

Architecture

Aitana provides multiple MCP integration approaches:

  • stdio MCP Server (mcp_stdio_compat.py) - Direct process communication
  • Works with both Claude Desktop and Claude Code
  • No HTTP overhead, fastest performance
  • Automatic client detection for analytics

2. HTTP/HTTPS Integration (Alternative)

  • HTTP MCP Server (/mcp and /mcp/mcp) - Web-based integrations
  • HTTPS MCP Server (app_https.py) - Secure local connections
  • Useful when stdio is not available

3. Dynamic MCP Tools (Within Assistants)

  • Registered MCP Servers (mcp_demo, mcp_database) - Pre-configured servers
  • External MCP Discovery (/direct/tools/mcp/discover) - Runtime discovery of external MCP servers
  • External MCP (external_mcp) - Runtime-configured connections
  • See Complete Architecture Guide for details

Claude Desktop & Claude Code Integration

  1. Install Backend Dependencies
    cd /Users/mark/dev/aitana-labs/frontend/backend
    uv sync
    
  2. Configure Claude Desktop

Recommended approach (includes gcloud auth and logging):

{
  "mcpServers": {
    "aitana": {
      "command": "/Users/mark/dev/aitana-labs/frontend/backend/mcp_server_claude_desktop.sh"
    }
  }
}

Alternative using UV directly (if you don’t need gcloud auth):

{
  "mcpServers": {
    "aitana": {
      "command": "/bin/bash",
      "args": [
        "-c",
        "cd /Users/mark/dev/aitana-labs/frontend/backend && /Users/mark/.local/bin/uv run mcp_stdio.py"
      ]
    }
  }
}

Note: The cd command is necessary because cwd parameter may not work reliably in Claude Desktop.

  1. Configure Claude Code

Option A: Share configuration from Claude Desktop:

claude mcp add-from-claude-desktop

Option B: Configure directly with UV:

{
  "mcpServers": {
    "aitana": {
      "command": "/bin/bash",
      "args": [
        "-c",
        "cd /Users/mark/dev/aitana-labs/frontend/backend && /Users/mark/.local/bin/uv run mcp_stdio_compat.py"
      ]
    }
  }
}

Note: Use mcp_stdio_compat.py for Claude Code due to parameter serialization compatibility. The cd ensures UV finds the project dependencies.

Alternative Setup Methods

Method A: Working Configuration (Tested)

{
  "mcpServers": {
    "aitana": {
      "command": "/Users/mark/dev/aitana-labs/frontend/backend/mcp_server_claude_desktop.sh"
    },
    "aitana_demo": {
      "command": "/Users/mark/.local/bin/uv",
      "args": ["run", "/Users/mark/dev/aitana-labs/frontend/backend/tools/mcp_tools/demo_server.py"]
    }
  }
}

This configuration works because:

  • Main server uses launcher script with gcloud auth
  • Demo server has inline dependencies (# /// script metadata)

Method B: Multiple MCP Servers with UV

{
  "mcpServers": {
    "aitana-main": {
      "command": "/Users/mark/dev/aitana-labs/frontend/backend/mcp_server_claude_desktop.sh"
    },
    "aitana-demo": {
      "command": "/bin/bash",
      "args": [
        "-c",
        "cd /Users/mark/dev/aitana-labs/frontend/backend && /Users/mark/.local/bin/uv run tools/mcp_tools/demo_server.py"
      ]
    }
  }
}

Method C: Using UV with –directory flag

{
  "mcpServers": {
    "aitana-demo": {
      "command": "/Users/mark/.local/bin/uv",
      "args": [
        "run",
        "--directory",
        "/Users/mark/dev/aitana-labs/frontend/backend",
        "tools/mcp_tools/demo_server.py"
      ]
    }
  }
}

Method D: Shell Script with Client Detection (Advanced)

For Claude Desktop (includes gcloud auth and logging):

{
  "mcpServers": {
    "aitana": {
      "command": "/Users/mark/dev/aitana-labs/frontend/backend/mcp_server_claude_desktop.sh"
    }
  }
}

Method E: Python Direct (with virtual environment)

{
  "mcpServers": {
    "aitana": {
      "command": "python",
      "args": ["/Users/mark/dev/aitana-labs/frontend/backend/mcp_stdio_compat.py"],
      "env": {
        "GOOGLE_CLOUD_PROJECT": "your-project",
        "GOOGLE_CLOUD_LOCATION": "global",
        "ANTHROPIC_API_KEY": "your-api-key"
      }
    }
  }
}

Multiple MCP Servers Configuration

You can configure Claude Desktop with multiple MCP servers simultaneously. Each appears as a separate tool source:

Working Configuration: Main + Demo Server (Tested ✅)

{
  "mcpServers": {
    "aitana": {
      "command": "/Users/mark/dev/aitana-labs/frontend/backend/mcp_server_claude_desktop.sh"
    },
    "aitana_demo": {
      "command": "/Users/mark/.local/bin/uv",
      "args": ["run", "/Users/mark/dev/aitana-labs/frontend/backend/tools/mcp_tools/demo_server.py"]
    }
  }
}

Why this works:

  • aitana: Launcher script handles gcloud auth and environment setup
  • aitana_demo: Uses inline script dependencies via uv run (automatically installs dependencies)

Alternative: Without Inline Dependencies

For scripts that rely on backend’s pyproject.toml dependencies:

{
  "mcpServers": {
    "my-server": {
      "command": "/bin/bash",
      "args": [
        "-c",
        "cd /Users/mark/dev/aitana-labs/frontend/backend && /Users/mark/.local/bin/uv run tools/mcp_tools/my_server.py"
      ]
    }
  }
}

Benefits of Multiple Servers

  1. Separation of Concerns: Different servers for different purposes
  2. Independent Updates: Update/restart servers individually
  3. Tool Organization: Group related tools together
  4. Permission Control: Different access levels per server

Creating Custom MCP Servers

⚠️ Common Pitfalls to Avoid:

  1. FastMCP doesn’t support description parameter - Use only name
  2. Scripts must be run with uv for inline dependencies to work
  3. command must be an executable - Not a Python script path

Option 1: Using Project Dependencies

Create a new server in backend/tools/mcp_tools/ that uses backend dependencies:

# my_custom_server.py
from fastmcp import FastMCP

mcp = FastMCP(name="My Custom Tools")

@mcp.tool()
def custom_tool(param: str) -> str:
    """Description of your custom tool"""
    return f"Processed: {param}"

if __name__ == "__main__":
    mcp.run()

Add to Claude Desktop configuration:

{
  "mcpServers": {
    "my-custom": {
      "command": "/bin/bash",
      "args": [
        "-c",
        "cd /Users/mark/dev/aitana-labs/frontend/backend && /Users/mark/.local/bin/uv run tools/mcp_tools/my_custom_server.py"
      ]
    }
  }
}

Option 2: Self-Contained Script with Inline Dependencies

Create a self-contained script with UV inline script metadata:

# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "fastmcp>=0.1.0",
# ]
# ///

from fastmcp import FastMCP

mcp = FastMCP(name="My Standalone Tools")

@mcp.tool()
def standalone_tool(text: str) -> str:
    """A standalone tool with its own dependencies"""
    return f"Processed: {text}"

if __name__ == "__main__":
    mcp.run()

This can be run directly with UV from any location:

{
  "mcpServers": {
    "standalone": {
      "command": "/Users/mark/.local/bin/uv",
      "args": ["run", "/path/to/standalone_server.py"]
    }
  }
}

About MCP Launcher Scripts

The launcher scripts (mcp_server_claude_desktop.sh) provide additional features:

  • Client Detection: Identifies Claude Desktop vs Claude Code
  • gcloud Authentication: Automatically configures Google Cloud auth
  • Logging: Rotates logs and tracks connections
  • Path Management: Finds UV and Python installations

For simple MCP servers that don’t need gcloud auth, using UV directly is simpler and sufficient.

Benefits of Client Detection:

  • Langfuse Analytics: Automatically adds user_id and session_id to traces
  • Debugging: Easily identify which client made each request
  • Client-specific behavior: Enable features based on client type
  • Session tracking: Stable session IDs for stdio connections

Note: The mcp_stdio_compat.py includes compatibility fixes for Claude Code parameter serialization. Once issue #3084 is resolved, Claude Code can use the simpler mcp_stdio.py.

Verify Connection

In Claude Code, the tools should appear with prefix mcp__aitana__:

  • mcp__aitana__user_history
  • mcp__aitana__ai_search
  • mcp__aitana__google_search
  • mcp__aitana__extract_files
  • mcp__aitana__structured_extraction
  • mcp__aitana__url_processing
  • mcp__aitana__gemini_model
  • mcp__aitana__anthropic_smart_model
  • mcp__aitana__smart_stream_model

Using Tools in Claude Code

# Example: Search user history
result = await mcp__aitana__user_history({
    "params": {
        "query": "AI",
        "email_or_domain": "user@example.com"
    }
})

# Example: Google search
result = await mcp__aitana__google_search({
    "params": {
        "query": "latest AI news"
    }
})

Alternative: HTTP/HTTPS Server Integration

For web-based MCP integration (instead of stdio), you can use the HTTP or HTTPS server:

HTTPS Setup

  1. Generate SSL Certificate
    cd /Users/mark/dev/aitana-labs/frontend/backend
    uv run python generate_ssl_cert.py
    
  2. Start HTTPS Server ```bash

    Using aitana CLI

    aitana server start –https

Or directly

cd backend && uv run app_https.py


3. **Configure Client**
URL: `https://localhost:1956/mcp/mcp`

### HTTP Setup

1. **Start HTTP Server**
```bash
# Using aitana CLI
aitana server start

# Or directly
cd backend && uv run app_fastapi.py
  1. Configure Client URL: http://localhost:1956/mcp

Available Tools

Assistant Interaction Tools (NEW)

assistant_list

List all available assistants that you have access to.

Parameters:

  • include_templates (bool, optional): Include template assistants, defaults to false
  • include_instances (bool, optional): Include assistant instances, defaults to true
  • limit (int, optional): Maximum number of assistants to return, defaults to 100

Example:

{
  "params": {
    "include_templates": false,
    "include_instances": true,
    "limit": 10
  }
}

assistant_inspect

Inspect a specific assistant’s configuration and available tools.

Parameters:

  • assistant_id (str, required): The ID of the assistant to inspect

Example:

{
  "params": {
    "assistant_id": "research-assistant-v1"
  }
}

assistant_call

Call an assistant with a prompt and get a response.

Parameters:

  • assistant_id (str, required): The ID of the assistant to call
  • prompt (str, required): The question or prompt to send
  • tools (list, optional): Override the assistant’s default tools
  • tool_configs (dict, optional): Tool configuration overrides
  • chat_history (list, optional): Previous conversation context
  • save_to_history (bool, optional): Save to Firestore, defaults to false

Example:

{
  "params": {
    "assistant_id": "research-assistant-v1",
    "prompt": "What are the latest developments in renewable energy?",
    "tools": ["ai-search", "google-search"],
    "save_to_history": false
  }
}

Information Retrieval Tools

user_history

Search through user’s chat history to find relevant conversations.

Parameters:

  • query (str, required): Search query term
  • email_or_domain (str, required): User email or domain to search
  • search_type (str, optional): ‘email’ or ‘domain’, defaults to ‘email’

Example:

{
  "params": {
    "query": "machine learning",
    "email_or_domain": "user@example.com",
    "search_type": "email"
  }
}

Search for information using Vertex AI semantic search.

Parameters:

  • question (str, required): The search query
  • datastore_id (str, optional): Specific datastore to search (e.g., “aitana3”, “bess-germany”)
  • filter_str (str, optional): Filter string for results
  • limit_content (bool, optional): Limit content length, defaults to True

Examples:

Default datastore:

{
  "params": {
    "question": "What is quantum computing?"
  }
}

Specific datastore (e.g., BESS Germany):

{
  "params": {
    "question": "battery storage market trends",
    "datastore_id": "bess-germany-datastore"
  }
}

With filtering:

{
  "params": {
    "question": "renewable energy policies",
    "datastore_id": "energy-datastore",
    "filter_str": "country:Germany AND year:2024"
  }
}

Search the web using Google Search and analyze results with AI.

Parameters:

  • query (str, required): The search query

Example:

{
  "params": {
    "query": "latest developments in renewable energy 2025"
  }
}

Content Processing Tools

extract_files

Extract and analyze content from files stored in Google Cloud Storage.

Parameters:

  • question (str, required): Question about the files
  • file_uris (list, required): List of GCS URIs to process
  • batch_size (int, optional): Files per batch, defaults to 20
  • timeout_seconds (int, optional): Timeout in seconds, defaults to 240

Example:

{
  "params": {
    "question": "Summarize the key findings",
    "file_uris": ["gs://bucket/report.pdf", "gs://bucket/data.csv"]
  }
}

structured_extraction

Extract structured data from text using custom or predefined schemas.

Parameters:

  • text (str, required): Text to extract from
  • schema (dict, optional): Custom extraction schema
  • schema_name (str, optional): Name of predefined schema

Example:

{
  "params": {
    "text": "John Doe, age 30, works at TechCorp as a Senior Engineer",
    "schema_name": "person"
  }
}

url_processing

Process and extract information from web URLs.

Parameters:

  • question (str, required): Question about the URLs
  • urls (list, required): List of URLs to process

Example:

{
  "params": {
    "question": "What are the main topics discussed?",
    "urls": ["https://example.com/article1", "https://example.com/article2"]
  }
}

AI Model Tools

gemini_model

Generate responses using Google Gemini models.

Parameters:

  • prompt (str, required): The prompt for the model
  • model_name (str, optional): Model to use, defaults to ‘gemini-2.5-flash’
  • temperature (float, optional): Temperature setting, defaults to 0.7
  • max_tokens (int, optional): Max tokens to generate, defaults to 2048

Example:

{
  "params": {
    "prompt": "Explain the concept of neural networks",
    "model_name": "gemini-2.0-flash-exp"
  }
}

anthropic_smart_model

Generate responses using Anthropic Claude models with smart processing.

Parameters:

  • prompt (str, required): The prompt for the model
  • model (str, optional): Model to use, defaults to ‘claude-3-5-sonnet-20241022’
  • temperature (float, optional): Temperature setting, defaults to 0.7

Example:

{
  "params": {
    "prompt": "Write a Python function to implement quicksort"
  }
}

smart_stream_model

Generate responses using unified smart streaming models.

Parameters:

  • prompt (str, required): The prompt for the model
  • model (str, optional): Model to use, defaults to ‘gemini-2.5-flash’

Example:

{
  "params": {
    "prompt": "Explain photosynthesis in simple terms"
  }
}

Client Detection & Analytics

How Client Detection Works

The MCP server automatically detects which client is connecting:

  1. Environment Variables: Launcher scripts set CLAUDE_DESKTOP_VERSION or CLAUDE_CODE_VERSION
  2. Script Detection: Falls back to detecting script name (mcp_stdio.py vs mcp_stdio_compat.py)
  3. HTTP Headers: For HTTP connections, checks X-MCP-Client and User-Agent headers

Langfuse Trace Enhancement

With client detection enabled, all Langfuse traces automatically include:

  • user_id: e.g., claude-desktop-mark or claude-code-mark
  • session_id: Stable hash for stdio sessions, random for HTTP
  • metadata: Client type, version, and connection mode

Example trace metadata:

{
  "user_id": "claude-desktop-mark",
  "session_id": "74c4fcfa7c44",
  "metadata": {
    "mcp_client": "claude-desktop",
    "mcp_metadata": {
      "version": "1.0",
      "mode": "stdio",
      "client_type": "claude-desktop"
    }
  }
}

Testing Client Detection

Verify client detection is working:

cd /Users/mark/dev/aitana-labs/frontend/backend
uv run python test_mcp_client_detection.py

This will test detection for:

  • Claude Desktop (stdio mode)
  • Claude Code (stdio-compat mode)
  • Aitana CLI (HTTP mode)
  • cURL and other HTTP clients

Real-World Example: BESS Market Analysis Demo

See MCP in action with our BESS Market Visualization Demo which showcases:

  • Using mcp__aitana__ai_search to gather market data
  • Synthesizing information from 10+ industry reports
  • Creating interactive visualizations from the data
  • Complete end-to-end automation with Claude Code

The demo was created entirely through conversation, demonstrating the power of MCP integration.

Usage Examples with Claude

Working with Assistants

Once configured, you can interact with assistants naturally in Claude:

Example 1: Discovering Assistants

Ask Claude: “List all available assistants”

Claude will use the assistant_list tool to show you available assistants.

Example 2: Inspecting an Assistant

Ask Claude: “Show me what the research assistant can do”

Claude will:

  1. Use assistant_list to find the research assistant
  2. Use assistant_inspect to get its configuration
  3. Show you its available tools and capabilities

Example 3: Using an Assistant

Ask Claude: “Ask the research assistant about renewable energy trends”

Claude will:

  1. Use assistant_call with the appropriate assistant ID
  2. Pass your question to the assistant
  3. Return the assistant’s response

Example 4: Complex Workflow

Ask Claude: “Find an assistant that can search documents, then use it to find information about solar panels”

Claude will:

  1. Use assistant_list to find assistants
  2. Use assistant_inspect to check which ones have document search
  3. Use assistant_call with the appropriate assistant and search query
  4. Present the results

Combining Multiple Tools

The assistant tools work seamlessly with other MCP tools:

You: "List my assistants, then use the one specialized in documents to search for renewable energy PDFs"

Claude will:
1. assistant_list → Get available assistants
2. assistant_inspect → Check capabilities
3. assistant_call → Call the document assistant
   - The assistant might use: ai_search, list_gcs_bucket, extract_files
4. Present comprehensive results

Testing & Debugging

Test MCP Connection

For stdio Server (Claude Code)

# Test directly
cd backend
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | uv run python mcp_stdio_compat.py

For HTTP/HTTPS Server (Claude Desktop)

# List all tools
curl -X POST http://localhost:1956/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'

# Call a specific tool
curl -X POST http://localhost:1956/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "google_search",
      "arguments": {"query": "test search"}
    }
  }'

Interactive Test Dashboard

Access the test dashboard at http://localhost:1956/test to:

  • View all available MCP tools
  • Test tool execution with custom parameters
  • Monitor server status and logs

Common Issues & Solutions

Issue: Tools not appearing in Claude Code

Solution:

  • Verify MCP server is in your Claude Code settings
  • Check environment variables are properly set
  • Restart Claude Code after configuration changes

Issue: “Invalid JSON in params” error

Solution:

  • Ensure parameters are passed as a dictionary within the params field
  • The compatibility wrapper (mcp_stdio_compat.py) handles both dict and string formats

Issue: SSL certificate error in Claude Desktop

Solution:

  • Accept the self-signed certificate warning
  • Or regenerate certificate: uv run python generate_ssl_cert.py

Issue: Connection refused

Solution:

  • Ensure the server is running (aitana server status)
  • Check firewall settings for port 1956
  • Verify correct protocol (HTTP vs HTTPS)

Environment Configuration

Required Environment Variables

# Google Cloud (for AI search, file extraction)
GOOGLE_CLOUD_PROJECT=your-project-id
GOOGLE_CLOUD_LOCATION=global

# Anthropic (for Claude models)
ANTHROPIC_API_KEY=sk-ant-...

# Optional: Langfuse for observability
LANGFUSE_SECRET_KEY=sk-lf-...
LANGFUSE_PUBLIC_KEY=pk-lf-...
LANGFUSE_HOST=https://cloud.langfuse.com

Setting Environment Variables

For Claude Code (stdio)

Add to the MCP server configuration in Claude Code settings:

{
  "env": {
    "GOOGLE_CLOUD_PROJECT": "your-project",
    "ANTHROPIC_API_KEY": "your-key"
  }
}

For Local Development

Create .env file in backend directory:

cd backend
cp .env.example .env
# Edit .env with your values

Advanced Configuration

Custom Tool Development

Add new tools to the MCP server:

# In mcp_tools.py or mcp_stdio_compat.py

@mcp.tool(
    description="""Your tool description here.
    
    Parameters (pass as dict in 'params'):
    - param1 (str, required): Description
    - param2 (int, optional): Description, defaults to value
    
    Example: {"params": {"param1": "value"}}
    """
)
async def your_custom_tool(params: Union[Dict[str, Any], str]) -> Dict[str, Any]:
    """Tool implementation."""
    
    # Handle both dict and string params
    if isinstance(params, str):
        params = json.loads(params)
    
    # Extract parameters
    param1 = params.get("param1", "")
    param2 = params.get("param2", 10)
    
    # Tool logic here
    result = process_data(param1, param2)
    
    return {
        "success": True,
        "result": result,
        "tool": "your_custom_tool"
    }

Performance Optimization

  1. Connection Pooling: The MCP server maintains connection pools for external services
  2. Caching: Results are cached where appropriate (15-minute TTL for searches)
  3. Async Operations: All tools use async/await for non-blocking operations
  4. Batch Processing: File extraction supports batch processing for efficiency

Migration Guide

From Old MCP Pattern to New Pattern

Old Pattern (Pre-0.144.5)

# Separate MCP server file
mcp_server = FastMCP("aitana")
# Manual tool registration

New Pattern (Current)

# Integrated with FastAPI app
app, vac_routes = VACRoutesFastAPI.create_app_with_mcp(
    title="Aitana Backend API",
    enable_mcp=True
)

# Dynamic tool registration
@vac_routes.add_mcp_tool
async def tool_name(...):
    ...

Updating Existing Integrations

  1. Update import paths: Use mcp_stdio_compat.py for Claude Code
  2. Update tool names: Add mcp__aitana__ prefix for Claude Code
  3. Update parameter format: Wrap parameters in params field
  4. Update server URLs: Use /mcp/mcp endpoint for HTTPS

External MCP Server Discovery

Overview

The Aitana backend supports discovering and connecting to external MCP servers at runtime. This enables integration with third-party MCP servers without requiring pre-configuration.

Discovery Endpoint

Endpoint: POST /direct/tools/mcp/discover

⚠️ Important: Note that this is a /direct/... endpoint, not /vac/direct/.... The Aitana backend has two endpoint patterns:

  • VAC endpoints (/vac/...) - Traditional assistant and streaming endpoints
  • Direct API endpoints (/direct/...) - Direct tool access for testing and integration

Purpose: Discover available tools from any external MCP server by providing its URL.

Parameters:

  • url (str, required): The MCP server URL
  • auth (str, optional): Authentication token if required

Response:

  • success (bool): Whether discovery succeeded
  • tools (array): List of available tools with their descriptions and parameters
  • server_id (str): Generated server identifier for future reference
  • tool_count (int): Number of tools discovered

Example: DeepWiki MCP Server

Request:

curl -X POST "http://localhost:1956/direct/tools/mcp/discover" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://mcp.deepwiki.com/mcp"}'

Response:

{
  "success": true,
  "tools": [
    {
      "name": "read_wiki_structure",
      "description": "Get a list of documentation topics for a GitHub repository",
      "server_id": "http_ef505ea3",
      "parameters": {
        "repoName": {
          "type": "string",
          "description": "GitHub repository: owner/repo (e.g. \"facebook/react\")",
          "required": true,
          "default": null
        }
      }
    },
    {
      "name": "read_wiki_contents",
      "description": "View documentation about a GitHub repository",
      "server_id": "http_ef505ea3",
      "parameters": {
        "repoName": {
          "type": "string",
          "description": "GitHub repository: owner/repo (e.g. \"facebook/react\")",
          "required": true,
          "default": null
        }
      }
    },
    {
      "name": "ask_question",
      "description": "Ask any question about a GitHub repository",
      "server_id": "http_ef505ea3",
      "parameters": {
        "repoName": {
          "type": "string",
          "description": "GitHub repository: owner/repo (e.g. \"facebook/react\")",
          "required": true,
          "default": null
        },
        "question": {
          "type": "string",
          "description": "The question to ask about the repository",
          "required": true,
          "default": null
        }
      }
    }
  ],
  "server_id": "http_ef505ea3",
  "tool_count": 3
}

Usage Notes

  • Server IDs: The system generates unique server IDs (like http_ef505ea3) for each discovered server
  • Tool Calling: After discovery, tools can be called using the standard MCP tool endpoints
  • Authentication: Some MCP servers may require authentication tokens
  • Error Handling: The API returns detailed error messages if connection fails

Integration Examples

With Aitana CLI:

# Test external MCP discovery (see CLI section below for more details)
aitana tool external_mcp -a '{"server_url": "https://mcp.deepwiki.com/mcp", "method": "tools/list"}'

With Assistant Configuration: External MCP servers can be configured within assistant tool configurations for dynamic integration.

External MCP Tools via Aitana CLI

The Aitana CLI provides comprehensive support for managing and calling external MCP servers that aren’t in the registry. This enables integration with any MCP-compatible server at runtime.

Managing External MCP Servers

Add an External Server

# Add DeepWiki MCP server
aitana tool mcp-ext add deepwiki https://mcp.deepwiki.com/mcp

# Add server with authentication
aitana tool mcp-ext add myserver https://api.example.com/mcp --auth your-api-key

List External Servers

# List all configured external servers
aitana tool mcp-ext list

# Show available tools from a specific server
aitana tool mcp-ext list deepwiki

# Get JSON output for scripting
aitana tool mcp-ext list deepwiki --json-output

Remove a Server

aitana tool mcp-ext remove deepwiki

Calling External MCP Tools

The CLI supports two execution modes for calling external MCP tools:

Direct Mode (Fast & Exact)

Direct mode passes your arguments directly to the MCP server without AI interpretation. Use this when you know the exact parameters required.

# Call with exact JSON arguments
aitana tool mcp-ext call deepwiki read_wiki_structure \
  -a '{"repoName":"facebook/react"}' \
  --mode direct

Characteristics:

  • ✅ Fast execution (no AI overhead)
  • ✅ Predictable results
  • ✅ Best for automation/scripting
  • ❌ Requires exact parameter names and formats
  • ❌ No natural language support

Anthropic Mode (Smart & Flexible) - Default

Anthropic mode uses Claude AI to intelligently interpret your request and map it to the correct tool parameters. This is the default mode.

# Method 1: With explicit arguments (AI uses provided params)
aitana tool mcp-ext call deepwiki read_wiki_structure \
  -a '{"repoName":"facebook/react"}'

# Method 2: Natural language context (AI extracts params)
aitana tool mcp-ext call deepwiki read_wiki_structure \
  -c "Get the wiki structure for facebook/react repository"

# Method 3: Both arguments and context (AI applies context to params)
aitana tool mcp-ext call deepwiki read_wiki_structure \
  -a '{"repoName":"facebook/react"}' \
  -c "Focus on the build system sections"

# Method 4: No parameters (AI prompts for required info)
aitana tool mcp-ext call deepwiki read_wiki_structure

Characteristics:

  • ✅ Natural language support
  • ✅ Intelligent parameter mapping
  • ✅ Helpful error messages
  • ✅ Context-aware responses
  • ❌ Slower (requires AI processing)
  • ❌ May interpret parameters differently than expected

Practical Examples

Example 1: Exploring a GitHub Repository

# Add the DeepWiki server
aitana tool mcp-ext add deepwiki https://mcp.deepwiki.com/mcp

# Discover available tools
aitana tool mcp-ext list deepwiki

# Get React documentation structure
aitana tool mcp-ext call deepwiki read_wiki_structure \
  -c "Show me the documentation for React"

# Ask a specific question
aitana tool mcp-ext call deepwiki ask_question \
  -c "How does React's Fiber architecture work in facebook/react?"

# Get exact README content (direct mode for predictable output)
aitana tool mcp-ext call deepwiki read_repo_readme \
  -a '{"repoName":"microsoft/vscode"}' \
  --mode direct

Example 2: Working with Multiple Servers

# Add multiple external servers
aitana tool mcp-ext add deepwiki https://mcp.deepwiki.com/mcp
aitana tool mcp-ext add weather https://weather-mcp.example.com/api
aitana tool mcp-ext add translator https://translate.example.com/mcp --auth $API_KEY

# List all servers
aitana tool mcp-ext list

# Call tools from different servers
aitana tool mcp-ext call weather get_forecast -c "Weather in San Francisco"
aitana tool mcp-ext call translator translate -a '{"text":"Hello","to":"es"}'

Example 3: Automation and Scripting

#!/bin/bash
# Script to analyze multiple repositories

REPOS=("facebook/react" "vuejs/vue" "angular/angular")

for repo in "${REPOS[@]}"; do
  echo "Analyzing $repo..."
  
  # Use direct mode for consistent output format
  aitana tool mcp-ext call deepwiki read_wiki_structure \
    -a "{\"repoName\":\"$repo\"}" \
    --mode direct \
    --json-output > "${repo//\//_}_structure.json"
done

Output Options

# Default human-readable output
aitana tool mcp-ext call deepwiki read_wiki_structure -a '{"repoName":"facebook/react"}'

# JSON output for parsing
aitana tool mcp-ext call deepwiki read_wiki_structure -a '{"repoName":"facebook/react"}' --json-output

# JSON output saved to file
aitana tool mcp-ext call deepwiki read_wiki_structure -a '{"repoName":"facebook/react"}' --json-output > result.json

Troubleshooting

Common Issues

  1. “Server not found” error
    # Check if server is added
    aitana tool mcp-ext list
       
    # Re-add if necessary
    aitana tool mcp-ext add servername https://server.url/mcp
    
  2. Authentication failures
    # Remove and re-add with correct auth
    aitana tool mcp-ext remove myserver
    aitana tool mcp-ext add myserver https://api.example.com/mcp --auth correct-token
    
  3. Tool execution errors in anthropic mode
    # Try with explicit arguments
    aitana tool mcp-ext call server tool_name -a '{"param":"value"}'
       
    # Or use direct mode for debugging
    aitana tool mcp-ext call server tool_name -a '{"param":"value"}' --mode direct
    

Best Practices

  1. Use direct mode for:
    • Automation and scripting
    • When you know exact parameters
    • Consistent, predictable output
    • Performance-critical operations
  2. Use anthropic mode for:
    • Interactive exploration
    • Natural language queries
    • When parameter names are unclear
    • Complex context-aware requests
  3. Parameter tips:
    • In anthropic mode, -a arguments are included in the AI prompt
    • Combine -a and -c for best results in anthropic mode
    • Use --json-output when parsing results programmatically
  4. Security considerations:
    • Store auth tokens in environment variables
    • Don’t commit tokens to version control
    • Regularly rotate authentication tokens

Production Deployment

Google Cloud Run Deployment

The MCP server is automatically deployed with the backend:

# Automatic deployment on push to branches
git push origin dev  # Deploys to development
git push origin test # Deploys to staging  
git push origin prod # Deploys to production

Production URLs

  • Development: https://aitana-backend-dev.run.app/mcp
  • Staging: https://aitana-backend-test.run.app/mcp
  • Production: https://aitana-backend-prod.run.app/mcp

Security Considerations

  1. Authentication: Production MCP endpoints require authentication tokens
  2. Rate Limiting: Implemented to prevent abuse
  3. Input Validation: All tool inputs are validated and sanitized
  4. Audit Logging: All tool executions are logged for security monitoring

Support & Resources

Documentation

Troubleshooting

  • Check server logs: aitana server logs -f
  • View MCP debug info: curl http://localhost:1956/mcp/debug
  • Test individual tools: Use the interactive test dashboard

Getting Help