# Morphed Intelligence MCP Server

This is a Model Context Protocol (MCP) server that provides Claude with access to the Morphed Intelligence Platform. Partners can use this to manage customer HubSpot portals, run diagnostics, generate custom documents, manage assignments, and invoke service agents directly through Claude.

## Quick Start Guides

- **Claude Online (OAuth)**: [QUICK_START.md](./QUICK_START.md) - Connect Claude Online with OAuth 2.0
- **Claude Desktop (Stdio)**: See [Claude Desktop Configuration](#claude-desktop-configuration) below
- **Production Deployment**: [DEPLOYMENT.md](./DEPLOYMENT.md) - Deploy to Render, Vercel, AWS, etc.
- **OAuth Server Details**: [OAUTH_SSE_SERVER.md](./OAUTH_SSE_SERVER.md) - Complete OAuth implementation guide

## Transport Options

This MCP server supports multiple transport protocols:

### 1. OAuth 2.0 + SSE (Recommended for Claude Online)
**Best for:** Claude Online custom connectors with secure authentication
```bash
npm run start:oauth
```

### 2. SSE/Streamable HTTP (Without OAuth)
**Best for:** Direct SSE connections without OAuth
```bash
npm run start:sse
```

### 3. HTTP Transport
**Best for:** Simple HTTP-based integrations
```bash
npm run start:http
```

### 4. Stdio Transport (Claude Desktop)
**Best for:** Claude Desktop app integration
```bash
npm start
```

## Features

### CRM Intelligence & Analytics
- **crm_dynamic_multi_query** - Query multiple CRM tables in one pass with flexible filters
- **crm_analytics** - Execute 60+ Supabase RPC functions for deep data analysis (contacts, companies, deals, tickets, activity, owner, revenue, marketing, system, health)
- **get_agent_context** - Fetch Morphed agent context and buyer-intent readiness
- **workbench_tab_insights** - Access Workbench Watch/Understand tab data
- **get_live_monitoring_overview** - Fetch live monitoring and observability context
- **external_signal_intelligence** - Inspect external and buyer-intent signals

### Diagnostic Reports
- **diagnostic_report** - Generate and manage diagnostic reports with 15+ built-in types:
  - portal-health, revops-readiness, ai-readiness, data-quality, workflow-collision, integration-health, email-deliverability, portal-architecture, form-conversion, property-taxonomy, lifecycle-scoring, deal-pipeline, security-permissions, governance-hardening, multi-portal-sync, sales-process-readiness, marketing-ops-fit, service-ops, partner-scalability
- Custom diagnostics via `customDiagnosticConfig` for bespoke analysis
- Living documents: ongoing monitoring dashboards that track findings over time
- Credit management: check available credits, purchase plans, share packs

### Custom Documents
- **custom_document** - Create and manage AI-generated documents and markdown exports
  - AI generation: architecture briefs, risk reports, strategic plans, analysis documents
  - Export formats: PDF, DOCX, XLSX, PPTX, CSV, TXT
  - Templates: create, list, and generate from reusable templates
  - Document management: list, get, download, update settings, queue auto-updates

### Portfolio Documents (Multi-Portal)
- **portfolio_document** - Generate diagnostics and documents across multiple customer portals
  - Cross-portal diagnostics: run the same diagnostic across your entire portfolio
  - Portfolio analysis documents: comparative and aggregated insights
  - Sync status: check data freshness across portals
  - Credit sharing: distribute diagnostic credits to partner portals

### Portfolio Overview & Health
- **get_portfolio_overview** - Partner-wide portfolio snapshot with workspace context
- **portfolio_health_ranking** - Rank customer portals by health score
- **portfolio_form_conversion** - Compare form conversion performance across portals
- **analyze_portfolio_performance** - Analyze performance across all customer portals
- **qbr_briefing** - Create QBR-style briefing package for a customer

### Governance & Managed Operations
- **manage_governance_layer** - Read or update governance state (policies, SLAs, violations, approvals)
- **managed_ops_control** - Work objects, approvals, audit trail, priority stack, verification

### Autonomous Agent Loop
- **get_work_object_chain** - Fetch full work object chain with decision logs
- **get_agent_activity** - Fetch recent autonomous agent activity
- **pause_chain** / **resume_chain** / **archive_chain** - Control active work object chains
- **get_hubspot_write_log** - View what agents have written to HubSpot
- **get_agent_run_schedule** - View autonomous agent scan schedules
- **trigger_agent_run** - Manually trigger autonomous agent scan

### Assignments & Service Agents
- **manage_assignment** - Interact with Morphed assignments directly
- **assignment_workflow** - Full assignment lifecycle management (the co-working flow)
- **invoke_service_agent** - Invoke service agents (intake-intelligence, scope-brief, build-review, documentation, governance-health, channel-agent)
- **agent_scheduling** - Manage autonomous agent run schedules
- **manage_agent_profiles** - Create, update, activate agent profiles and tasks
- **manage_agent_context** - Manage agent context entries
- **agent_workspace** - Access Workbench Do suggestions, thread history, memories

### Partner & Customer Management
- **get_partner_info** - Get enriched partner account information
- **get_partner_data** - Get partner profile data with CRM data, health scores, portfolio diagnostics
- **validate_api_key** - Legacy internal authentication diagnostic
- **list_customer_portals** - List all customer portals connected to partner
- **add_customer_portal** - Add customer HubSpot portal via OAuth
- **get_partner_customer_portals** - List portals with sync timestamps
- **sync_partner_customer_data** - Sync fresh HubSpot data for customer portals
- **analyze_customer_portal** - Deep analysis of a specific customer HubSpot portal
- **get_customer_metrics** - Key metrics and KPIs using 60+ CRM analytics RPCs

### Partner Content Library
- **search_partner_content** - Search partner content library (methodologies, templates, frameworks)
- **get_content_details** - Get full details of a specific content item
- **upload_partner_content** - Upload new content to partner library
- **fetch_partner_embedded_data** - Fetch embedded partner content (methodologies, case studies, playbooks)

### Proactive Monitoring & Alerts
- **setup_proactive_monitoring** - Set up proactive monitoring for HubSpot changes
- **get_proactive_monitoring_status** - Get current monitoring preferences and status
- **create_proactive_alert** / **list_proactive_alerts** / **delete_proactive_alert** - Manage custom proactive alerts
- **run_proactive_query** - Immediately run proactive monitoring query

### Customer Communication
- **create_customer_notification** - Create notifications/tasks in customer HubSpot portals
- **scrape_website** - Scrape and extract content from a website URL

### Utility
- **get_mcp_api_key** - Return OAuth connector setup details for older clients that still call the legacy tool name
- **get_package_version** - Return MCP server package version

## Installation

### Quick Install

```bash
cd morphed-mcp-server
npm install
```

### Configuration

Create `.env.local` file:
```bash
# Backend API URL
MORPHED_API_URL=http://localhost:5000

# Hosted OAuth connector
PUBLIC_MCP_URL=https://your-server.com
MCP_PORT=3002
```

### Start the Server

Choose your transport mode:

```bash
# OAuth + SSE (for Claude Online)
npm run start:oauth

# Legacy SSE wrapper
npm run start:sse

# HTTP transport
npm run start:http

# Stdio for local development
npm start

# Development mode (with debugger)
npm run dev:oauth
npm run dev:sse
npm run dev:http
npm run dev
```

## Claude and ChatGPT Connector Setup

For hosted MCP clients, add the Morphed connector URL:

```text
https://mcp.morphed.io/mcp
```

Claude, ChatGPT, and compatible clients discover the Morphed OAuth endpoints from that URL. The user signs in with Morphed, chooses the portal, approves access, and Morphed issues the connector token behind the scenes.

For local development, you can still run the stdio server directly:

```json
{
  "mcpServers": {
    "morphed": {
      "command": "node",
      "args": ["./server.mjs"],
      "env": {
        "MORPHED_API_URL": "http://localhost:5000"
      },
      "cwd": "/path/to/morphed-mcp-server"
    }
  }
}
```

## Usage Examples

Once connected, you can ask Claude to:

### Customer Portfolio
- "Show me my customer portal status"
- "List all my connected HubSpot portals"
- "Rank my portals by health score"

### Diagnostics
- "Run a portal-health diagnostic for customer portal 12345"
- "Generate a data-quality diagnostic for my SaaS client"
- "Run a revops-readiness check across my entire portfolio"

### Custom Documents
- "Create an architecture brief for portal 12345"
- "Generate a risk report for my top 3 at-risk customers"
- "Export a strategic plan as a PDF for our QBR"

### Portfolio Analysis
- "Compare form conversion performance across all my portals"
- "Create a QBR briefing for customer portal 67890"
- "Analyze performance across all my customer portals"

### Assignments & Agents
- "Create an assignment for the data migration project"
- "Invoke the governance-health agent for portal 12345"
- "Show me recent autonomous agent activity"

### Governance
- "Check governance policy compliance for my portfolio"
- "Show me the audit trail for the last work object"
- "What SLA violations have been flagged this month?"

## Troubleshooting

### 401 Authentication Errors

1. **Connector URL**: Make sure the client is using `https://mcp.morphed.io/mcp`, or your deployment's `/mcp` URL.
2. **OAuth session**: Reconnect the tool and complete the Morphed sign-in flow.
3. **Portal access**: Ensure the selected portal is available to the signed-in Morphed user.

### Debug Mode

Enable debug logging by setting:
```bash
DEBUG=true
```

### Common Issues

- **"OAuth required"**: Add the `/mcp` connector URL and complete Morphed sign-in
- **"Partner not found"**: Your HubSpot portal is not registered as a partner
- **"Partner account inactive"**: Your partner account needs to be activated
- **"spawn npx ENOENT"**: Node.js is not installed

## Authentication Flow

1. **Connector added**: User pastes the Morphed `/mcp` URL into Claude, ChatGPT, or another MCP client.
2. **Morphed sign-in**: The user signs in through the hosted Morphed OAuth page.
3. **Portal consent**: The user chooses the portal and approves connector access.
4. **Token issue**: Morphed issues scoped connector tokens behind the scenes.
5. **Governed access**: Tool calls run through Morphed portal access, approvals, and audit logging.

This ensures secure, tenant-isolated access to customer data through the MCP interface.

## Security

- Hosted connector access uses Morphed OAuth and portal consent
- Data is transmitted securely over HTTPS
- No customer data is stored locally by the MCP server
- All operations are logged for audit purposes

## Support

For support with the Morphed MCP server:
1. Check the logs for detailed error messages
2. Verify your configuration matches the examples
3. Contact your Morphed platform administrator
