Skip to Content

Mcp Server

SAM AI - MCP SERVER DOCUMENTATION

Last Updated: 2025-11-04
Status: INTEGRATED INTO AI_SAM CORE
Module: ai_sam (was ai_sam_claude_mcp, merged 2025-11-04)


WHAT IS MCP?

MCP (Model Context Protocol) is Anthropic's standard protocol for connecting AI assistants
to external data sources. It allows Claude Desktop and Claude mobile apps to access your
Odoo data from anywhere.

Official Spec: https://modelcontextprotocol.io/


ARCHITECTURE OVERVIEW

┌─────────────────────────────────────────────────────────────┐
│ MOBILE/DESKTOP (Anywhere)                                   │
│                                                              │
│  User asks Claude: "What's the Johnson project status?"     │
│      ↓                                                       │
│  Claude.ai / Claude Desktop / Claude Mobile                 │
│      ↓                                                       │
│  MCP Protocol (Anthropic standard)                          │
└──────────────────────────────────────────────────────────────┘
                         ↓
┌─────────────────────────────────────────────────────────────┐
│ MCP SERVER (Standalone Python process)                      │
│                                                              │
│  odoo_mcp_server.py                                         │
│  Generated by: ai_sam module                                │
│      ↓                                                       │
│  odoorpc library (JSON-RPC connection)                      │
└──────────────────────────────────────────────────────────────┘
                         ↓
┌─────────────────────────────────────────────────────────────┐
│ ODOO INSTANCE (Your server)                                 │
│                                                              │
│  ai_brain (data layer)                                      │
│  ai_sam (framework with MCP generator)                      │
│  ai_sam_workflows (workflow canvas)                         │
└──────────────────────────────────────────────────────────────┘

HOW IT WORKS

Phase 1: Configuration (In Odoo)

  1. User navigates to SAM AI → MCP Servers → Create
  2. Configures server settings:
  3. Server name: "Odoo SAM AI"
  4. Odoo URL: http://localhost:8069
  5. Database: your_database
  6. Features: Projects, CRM, Sales, etc.
  7. Clicks "Generate Files"
  8. Downloads odoo_mcp_server.py

Phase 2: Installation (On user's machine)

  1. Install dependencies: pip install odoorpc mcp
  2. Save script: C:\mcp_servers\odoo_sam\odoo_mcp_server.py
  3. Configure Claude Desktop config (~/.claude/config.json):
    json { "mcpServers": { "odoo": { "command": "python", "args": ["C:/mcp_servers/odoo_sam/odoo_mcp_server.py"], "env": { "ODOO_URL": "http://localhost:8069", "ODOO_DB": "your_database", "ODOO_USERNAME": "admin", "ODOO_PASSWORD": "your_password" } } } }
  4. Restart Claude Desktop

Phase 3: Usage (Anywhere)

User can now ask Claude (on phone, desktop, or web):
- "Show my Odoo projects"
- "List tasks for the Johnson project"
- "Find contact information for Sarah Smith"
- "What sales orders are pending?"

Claude connects to MCP server → MCP server queries Odoo → Results returned


FILE LOCATIONS (After Merge)

Models

ai_sam/models/mcp_server_config.py
  - sam.mcp.server.config (main config model)
  - sam.mcp.feature (individual MCP tools/features)

Services

ai_sam/services/mcp_server_generator.py
  - mcp.server.generator (AbstractModel)
  - generate_server_script() - Creates odoo_mcp_server.py
  - generate_manifest() - Creates manifest.json

Controllers

ai_sam/controllers/mcp_download_controller.py
  - /mcp/download/script/<config_id> - Download .py file
  - /mcp/download/bundle/<config_id> - Download .mcpb bundle
  - /mcp/download/manifest/<config_id> - Download manifest.json

Views

ai_sam/views/mcp_server_config_views.xml
  - Form view (configuration UI)
  - Tree view (list of configs)
  - Search view (filters)
  - Menu items

Security

ai_sam/security/ir.model.access.csv
  - access_sam_mcp_server_config_user
  - access_sam_mcp_server_config_system
  - access_sam_mcp_feature_user
  - access_sam_mcp_feature_system

CONFIGURATION MODEL FIELDS

Basic Information

  • server_name: Display name (e.g., "Odoo SAM AI")
  • version: Server version (e.g., "1.0.0")
  • description: Human-readable description

Connection Settings

  • odoo_url: Odoo instance URL (auto-detected)
  • odoo_database: Database name (auto-detected)
  • auth_method: user_password or api_key
  • default_username: Default username for MCP server

Feature Flags (Boolean)

  • enable_projects: Projects & Tasks module
  • enable_crm: CRM & Contacts
  • enable_sales: Sales Orders
  • enable_invoices: Invoices
  • enable_hr: HR & Employees
  • enable_inventory: Inventory & Stock

Custom Models

  • enable_custom_models: Allow custom model exposure
  • custom_model_ids: Many2many to ir.model (select any Odoo model)

Generated Files (Binary attachments)

  • server_script: odoo_mcp_server.py content
  • mcpb_bundle: .mcpb bundle (future feature)
  • manifest_json: manifest.json content

Status & Testing

  • state: draft | generating | ready | error
  • test_status: not_tested | testing | success | failed
  • test_message: Test results
  • generation_log: Generation progress log

Computed Fields

  • tool_count: Number of MCP tools that will be generated
  • estimated_size: Estimated file size
  • server_script_filename: odoo_sam_ai_mcp_server.py
  • mcpb_bundle_filename: odoo_sam_ai_v1.0.0.mcpb

GENERATED MCP TOOLS

The generated odoo_mcp_server.py contains these tools:

Projects Module (if enabled)

search_projects(query, active_only)
  - Search projects by name or partner
  - Returns: List of projects with client, start date, task count

get_project(project_id)
  - Get detailed project information
  - Returns: Project details + recent tasks

list_tasks(project_id, limit)
  - List tasks for a specific project
  - Returns: Tasks with stage, priority, deadline

CRM Module (if enabled)

search_contacts(query)
  - Search contacts by name, email, or phone
  - Returns: Contact list with details

get_contact(contact_id)
  - Get detailed contact information
  - Returns: Full contact card (email, phone, address, etc.)

Sales Module (if enabled)

search_sales_orders(query)
  - Search sales orders

get_sales_order(order_id)
  - Get order details + line items

Custom Models (if enabled)

search_{model_name}(query)
  - Generic search for custom model

get_{model_name}(record_id)
  - Get details for custom model record

Tool Generation Logic:
- Standard features: 2-4 tools per module
- Custom models: 2 tools per model (search + get)
- Total tools calculated automatically


MCP SERVER GENERATOR LOGIC

Generation Process

Step 1: Build Script Parts

script_parts = [
    header,           # File header with metadata
    imports,          # Python imports (odoorpc, mcp, asyncio)
    server_class,     # OdooMCPServer class definition
    list_tools,       # async list_tools() method
    call_tool,        # async call_tool() method
    implementations,  # Tool implementation methods
    main,            # Main execution (asyncio.run)
]

Step 2: Generate Each Section
- Header: Includes config summary (URL, DB, features enabled)
- Server class: Initializes odoorpc connection
- List tools: Returns Tool objects based on enabled features
- Call tool: Routes tool name to implementation method
- Implementations: Actual odoorpc queries for each tool
- Main: Async entry point using stdio_server

Step 3: Encode & Store

script = '\n\n'.join(script_parts)
encoded = script.encode('utf-8')
record.write({'server_script': base64.b64encode(encoded)})

CONNECTION TESTING

The model includes action_test_connection() which:

  1. Imports odoorpc (checks if installed)
  2. Parses odoo_url to extract host, port, protocol
  3. Creates odoorpc.ODOO connection
  4. Attempts login with default credentials
  5. Queries res.partner to verify access
  6. Returns success/failure message

Test Button: Available in form view header
Result: Displayed in "Connection Test" tab


AUTHENTICATION OPTIONS

Option 1: Username/Password (Current)

"env": {
  "ODOO_USERNAME": "admin",
  "ODOO_PASSWORD": "your_password"
}

Pros: Simple, works immediately
Cons: Password in config file, less secure

Option 2: API Key (Future)

"env": {
  "ODOO_API_KEY": "your_api_key_here"
}

Pros: More secure, revocable
Cons: Requires Odoo API key authentication setup
Status: Planned, not yet implemented


INTEGRATION WITH API INFRASTRUCTURE

Current State (2025-11-04)

MCP server uses hardcoded credentials from config.

Planned Integration

MCP server should read from existing API infrastructure:

# Instead of environment variables:
provider = odoo.env['api.service.provider'].search([
    ('service_type_name', '=', 'Odoo'),
], limit=1)

# Use OAuth tokens:
access_token = provider.oauth_access_token

Benefits:
- Single source of truth for credentials
- OAuth token refresh handled automatically
- Consistent with API orchestration system

Related Models:
- api.service.provider (ai_brain) - OAuth tokens
- api_credentials (ai_brain) - Workflow credentials
- api.operation.log (ai_brain) - API call logging


USE CASES

Use Case 1: Mobile Project Updates

Scenario: User is driving, receives call about project status
Flow:
1. After call, user asks Claude on phone: "What's the status of the Johnson project?"
2. Claude connects to MCP server at home/office
3. MCP server queries Odoo
4. Claude responds: "Johnson Website Redesign is 75% complete, 9 of 12 tasks done, deadline Friday"

Use Case 2: Client Meeting Quick Lookup

Scenario: In client meeting, need contact info
Flow:
1. User discreetly asks Claude on phone: "Find Sarah Smith's email"
2. MCP server searches Odoo CRM
3. Claude responds with contact details
4. User can continue conversation without interruption

Use Case 3: Weekend Planning

Scenario: Planning next week from home, Odoo not open
Flow:
1. User asks Claude Desktop: "What tasks are due next week?"
2. MCP server queries Odoo project.task
3. Claude lists tasks with priorities and deadlines
4. User can plan work week without opening Odoo


DEPLOYMENT OPTIONS

Option A: Local MCP Server (Current)

User's Machine:
  - Claude Desktop installed
  - Python + odoorpc + mcp installed
  - odoo_mcp_server.py running when Claude Desktop starts
  - Connects to local Odoo (localhost:8069)

Pros: Simple, fast, private
Cons: Only works when machine is on, localhost only

Option B: Remote MCP Server (Future)

Cloud Server:
  - odoo_mcp_server.py running as service
  - Connects to production Odoo instance
  - Accessible from anywhere

Pros: Always available, works on mobile
Cons: Requires cloud hosting, firewall configuration

Option C: Odoo Module MCP Endpoint (Future)

Odoo Module:
  - MCP endpoints built into Odoo
  - No separate server process needed
  - Claude connects directly to Odoo

Pros: No separate server, always in sync
Cons: Requires Odoo to be publicly accessible


LIMITATIONS & FUTURE ENHANCEMENTS

Current Limitations

  • ❌ Read-only (no create/update/delete operations)
  • ❌ Username/password auth only (no API keys)
  • ❌ No rate limiting
  • ❌ No caching layer
  • ❌ No multi-user support (one config per install)
  • ❌ No real-time updates (polling only)

Planned Enhancements

Phase 1: Write Operations
- Add create_project, update_task, etc.
- Require user confirmation for writes
- Audit log for all changes

Phase 2: OAuth Integration
- Use api.service.provider for credentials
- Token refresh handling
- Revocable access

Phase 3: Orchestration Integration
- Expose orchestration search results via MCP
- Tools: get_recent_searches, execute_search
- Cached results for faster responses

Phase 4: Workflow Execution
- Tool: run_workflow(workflow_name)
- Tool: get_workflow_status(execution_id)
- Remote workflow triggering

Phase 5: Advanced Features
- Real-time notifications via WebSocket
- Caching layer (5-min TTL)
- Rate limiting and quota management
- Multi-database support
- Team/shared configurations


TROUBLESHOOTING

Issue: "odoorpc not installed"

Solution:

pip install odoorpc mcp

Issue: "Connection failed"

Causes:
- Odoo not running
- Wrong URL/port
- Firewall blocking connection
- Wrong database name

Debug:
1. Test Odoo in browser: http://localhost:8069
2. Check Odoo is running: ps aux | grep odoo (Linux) or Task Manager (Windows)
3. Verify database name in Odoo
4. Test connection from Odoo: "Test Connection" button

Issue: "Authentication failed"

Causes:
- Wrong username/password
- User account disabled
- Database doesn't exist

Debug:
1. Try logging into Odoo web interface with same credentials
2. Check user exists: Settings → Users
3. Verify database name matches exactly

Issue: "Claude Desktop not showing MCP tools"

Causes:
- Config file not in correct location
- JSON syntax error in config
- Claude Desktop not restarted

Debug:
1. Verify config location: ~/.claude/config.json (Mac/Linux) or %APPDATA%\Claude\config.json (Windows)
2. Validate JSON syntax: Use JSONLint.com
3. Restart Claude Desktop completely
4. Check Claude Desktop logs


SECURITY CONSIDERATIONS

Credential Storage

  • ⚠️ Credentials stored in Claude Desktop config file
  • ⚠️ Plain text (not encrypted)
  • ✅ Only readable by user account
  • 🔒 Recommendation: Use API keys (when implemented)

Network Security

  • ✅ Localhost connections (default) are safe
  • ⚠️ Remote connections require HTTPS
  • ⚠️ Firewall rules needed for remote access
  • 🔒 Recommendation: Use VPN for remote MCP servers

Data Access

  • ✅ MCP server uses Odoo's permission system
  • ✅ User sees only what they have access to
  • ⚠️ No additional permission layer in MCP server
  • 🔒 Recommendation: Create dedicated MCP user with limited access

Audit Trail

  • ❌ MCP operations not logged in Odoo currently
  • ✅ Odoo's standard access logs apply
  • 🔒 Recommendation: Implement api.operation.log integration


CHANGELOG

2025-11-04: MCP server merged into ai_sam core
- Moved from ai_sam_claude_mcp → ai_sam
- Removed installer components (handled by desktop installer)
- Focused on MCP server generation only
- Module count reduced: 5 → 4

2025-10-XX: Initial MCP server implementation
- Created ai_sam_claude_mcp module
- Included environment installer
- MCP server generator
- VS Code/Claude Desktop installer


SUPPORT

For MCP Issues:
- Check Odoo logs: /var/log/odoo/odoo-server.log
- Check Claude Desktop logs
- Test connection button in Odoo
- Verify odoorpc can connect: python -c "import odoorpc; print('OK')"

For Feature Requests:
- Document in ai_sam/dev_docs/
- Discuss architectural impact
- Consider API integration


Document maintained by: SAM AI Team
Last reviewed: 2025-11-04
Next review: After successful deployment and testing

Was this helpful?