#
tokens: 7022/50000 12/12 files
lines: off (toggle) GitHub
raw markdown copy
# Directory Structure

```
├── .env.example
├── .gitignore
├── Dockerfile
├── examples
│   ├── python-client-example.py
│   └── typescript-client-example.ts
├── install.sh
├── LICENSE
├── package-lock.json
├── package.json
├── README.md
├── run-server.sh
├── smithery.yaml
├── src
│   └── index.ts
└── tsconfig.json
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
.DS_Store
node_modules
build
.env
dist*
```

--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------

```
# Octagon API Key
OCTAGON_API_KEY=your_octagon_api_key_here

# Base URL for Octagon API
OCTAGON_API_BASE_URL=https://api.octagonagents.com/v1 
```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
# Octagon: MCP for Market Data 

[![smithery badge](https://smithery.ai/badge/@OctagonAI/octagon-mcp-server)](https://smithery.ai/server/@OctagonAI/octagon-mcp-server)

![Favicon](https://docs.octagonagents.com/logo.svg) The Octagon MCP server provides specialized AI-powered financial research and analysis by integrating with the Octagon Market Intelligence API, enabling users to easily analyze and extract detailed insights from public filings, earnings call transcripts, financial metrics, stock market data, and extensive private market transactions within Claude Desktop and other popular MCP clients.

[![Demo](https://docs.octagonagents.com/financial_model_demo_fast.gif)](https://docs.octagonagents.com/financial_model_demo.mp4)

## Features

✅ **Comprehensive Market Intelligence** - Orchestrates multiple specialized agents for complete market analysis
   - SEC filings analysis and data extraction (8000+ public companies 10-K, 10-Q, 8-K, 20-F, S-1)
   - Earnings call transcript analysis (10 yrs of historical and current)
   - Financial metrics and ratios analysis (10 yrs of historical and current)
   - Stock market data access (over 10,000 active tickers, daily historical and current)
   - Private company research (3M+ companies)
   - Funding rounds and venture capital research (500k+ deals)
   - M&A and IPO transaction research (2M+ deals)
   - Institutional holdings and Form 13F filings
   - Cryptocurrency market data and analysis
     
✅ **Deep Research Capabilities** - Comprehensive research tools that can aggregate information from multiple sources
   
✅ **Web Scraping** - Extract structured data from any public website (json, csv, python scripts)

## Get Your Octagon API Key

To use Octagon MCP, you need to:

1. Sign up for a free account at [Octagon](https://app.octagonai.co/signup/?redirectToAfterSignup=https://app.octagonai.co/api-keys)
2. After logging in, from left menu, navigate to **API Keys** 
3. Generate a new API key
4. Use this API key in your configuration as the `OCTAGON_API_KEY` value

## Prerequisites

Before installing or running Octagon MCP, you need to have `npx` (which comes with Node.js and npm) installed on your system.

### Mac (macOS)

1. **Install Homebrew** (if you don't have it):
   ```bash
   /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
   ```
2. **Install Node.js (includes npm and npx):**
   ```bash
   brew install node
   ```
   This will install the latest version of Node.js, npm, and npx.

3. **Verify installation:**
   ```bash
   node -v
   npm -v
   npx -v
   ```

### Windows

1. **Download the Node.js installer:**
   - Go to [https://nodejs.org/](https://nodejs.org/) and download the LTS version for Windows.
2. **Run the installer** and follow the prompts. This will install Node.js, npm, and npx.
3. **Verify installation:**
   Open Command Prompt and run:
   ```cmd
   node -v
   npm -v
   npx -v
   ```

If you see version numbers for all three, you are ready to proceed with the installation steps below.

## Installation

### Running on Claude Desktop

To configure Octagon MCP for Claude Desktop:

1. Open Claude Desktop
2. Go to Settings > Developer > Edit Config
3. Add the following to your `claude_desktop_config.json` (Replace `your-octagon-api-key` with your Octagon API key):
```json
{
  "mcpServers": {
    "octagon-mcp-server": {
      "command": "npx",
      "args": ["-y", "octagon-mcp@latest"],
      "env": {
        "OCTAGON_API_KEY": "YOUR_API_KEY_HERE"
      }
    }
  }
}
```
4. Restart Claude for the changes to take effect

### Running on Cursor

Configuring Cursor Desktop 🖥️
Note: Requires Cursor version 0.45.6+

To configure Octagon MCP in Cursor:

1. Open Cursor Settings
2. Go to Features > MCP Servers 
3. Click "+ Add New MCP Server"
4. Enter the following:
   - Name: "octagon-mcp" (or your preferred name)
   - Type: "command"
   - Command: `env OCTAGON_API_KEY=your-octagon-api-key npx -y octagon-mcp`

> If you are using Windows and are running into issues, try `cmd /c "set OCTAGON_API_KEY=your-octagon-api-key && npx -y octagon-mcp"`

Replace `your-octagon-api-key` with your Octagon API key.

After adding, refresh the MCP server list to see the new tools. The Composer Agent will automatically use Octagon MCP when appropriate, but you can explicitly request it by describing your investment research needs. Access the Composer via Command+L (Mac), select "Agent" next to the submit button, and enter your query.

### Running on Windsurf

Add this to your `./codeium/windsurf/model_config.json`:

```json
{
  "mcpServers": {
    "octagon-mcp-server": {
      "command": "npx",
      "args": ["-y", "octagon-mcp@latest"],
      "env": {
        "OCTAGON_API_KEY": "YOUR_API_KEY_HERE"
      }
    }
  }
}
```

### Running with npx

```bash
env OCTAGON_API_KEY=your_octagon_api_key npx -y octagon-mcp
```

### Manual Installation

```bash
npm install -g octagon-mcp
```

## Documentation

For comprehensive documentation on using Octagon agents, please visit our official documentation at:
[https://docs.octagonagents.com](https://docs.octagonagents.com)

The documentation includes:
- Detailed API references
- Agent-specific query guidelines
- Examples and use cases
- Best practices for investment research

## Available Tools

Each tool uses a single `prompt` parameter that accepts a natural language query. Include all relevant details in your prompt.

### octagon-agent
**[COMPREHENSIVE MARKET INTELLIGENCE]** Orchestrates all agents for comprehensive market intelligence analysis. Combines insights from SEC filings, earnings calls, financial metrics, stock data, institutional holdings, private company research, funding analysis, M&A transactions, investor intelligence, and debt analysis.

**Best for:** Complex research requiring multiple data sources and comprehensive analysis across public and private markets.

**Example queries:**
```
Retrieve year-over-year growth in key income-statement items for AAPL, limited to 5 records and filtered by period FY
Analyze the latest 10-K filing for AAPL and extract key financial metrics and risk factors
Retrieve the daily closing prices for AAPL over the last 30 days
Analyze AAPL's latest earnings call transcript and extract key insights about future guidance
Provide a comprehensive overview of Stripe, including its business model and key metrics
Retrieve the funding history for Stripe, including all rounds and investors
Compare the financial performance of Tesla, Ford, and GM over the last 3 years
What was Microsoft's acquisition of GitHub valued at and what were the strategic reasons?
Analyze institutional ownership changes for NVIDIA over the past 6 months
```

### octagon-scraper-agent
**[PUBLIC & PRIVATE MARKET INTELLIGENCE]** Specialized agent for financial data extraction from investor websites. Extract structured financial data from investor relations websites, tables, and online financial sources.

**Best for:** Gathering financial data from websites that don't have accessible APIs.

**Example queries:**
```
Extract all data fields from zillow.com/san-francisco-ca/
Extract all data fields from www.carvana.com/cars/
Extract financial metrics from tesla.com/investor-relations
Extract pricing data from salesforce.com/products/platform/pricing/
```

### octagon-deep-research-agent
**[PUBLIC & PRIVATE MARKET INTELLIGENCE]** A comprehensive agent that can utilize multiple sources for deep research analysis. Aggregate research across multiple data sources, synthesize information, and provide comprehensive investment research.

**Best for:** Investment research questions requiring up-to-date aggregated information from the web.

**Example queries:**
```
Research the financial impact of Apple's privacy changes on digital advertising companies' revenue and margins
Analyze the competitive landscape in the cloud computing sector, focusing on AWS, Azure, and Google Cloud margin and growth trends
Investigate the factors driving electric vehicle adoption and their impact on battery supplier financials
Research the impact of AI adoption on semiconductor demand and pricing trends
Analyze the regulatory environment for cryptocurrency and its impact on crypto exchange valuations
```

## Example Queries

1. "What were Amazon's revenue and net income figures in Q4 2023?"
2. "Analyze Tesla's R&D spending trends over the last 3 years."
3. "What guidance did NVIDIA's CEO provide regarding AI chip demand in their latest earnings call?"
4. "Compare the price-to-earnings, price-to-sales, and EV/EBITDA ratios for the top 5 semiconductor companies."
5. "What was Anthropic's latest funding round size, valuation, and key investors?"
6. "Extract all data fields from zillow.com/san-francisco-ca/"
7. "Research the financial impact of Apple's privacy changes on digital advertising companies' revenue and margins"
8. "How many investments did Andreessen Horowitz make in AI startups in the last 12 months?"
9. "Retrieve historical Bitcoin price data from 2023 and analyze the price volatility trends"
10. "Analyze the competitive dynamics in the EV charging infrastructure market"

## Troubleshooting

1. **API Key Issues**: Ensure your Octagon API key is correctly set in the environment or config file.
2. **Connection Issues**: Make sure the connectivity to the Octagon API is working properly.
3. **Rate Limiting**: If you encounter rate limiting errors, reduce the frequency of your requests.

## License

MIT 

## Individual Specialized MCP Servers

While this server provides comprehensive market intelligence combining all our specialized agents, you can also use our individual MCP servers for specific use cases:

### Public Market Data Servers
- **[Octagon SEC Filings MCP](https://github.com/OctagonAI/octagon-sec-filings-mcp)** - Dedicated server for SEC filings analysis
- **[Octagon Earnings Transcripts MCP](https://github.com/OctagonAI/octagon-earnings-transcripts-mcp)** - Specialized for earnings call transcript analysis
- **[Octagon Stock Market Data MCP](https://github.com/OctagonAI/octagon-stock-market-data-mcp)** - Focused on stock market data access
- **[Octagon Financial Statements MCP](https://github.com/OctagonAI/octagon-financial-statements-mcp)** - Financial metrics and ratios analysis
- **[Octagon 13F Holdings MCP](https://github.com/OctagonAI/octagon-13f-holdings-mcp)** - Institutional ownership and Form 13F filings

### Private Market Data Servers
- **[Octagon Private Companies MCP](https://github.com/OctagonAI/octagon-private-companies-mcp)** - Private company research and intelligence
- **[Octagon Investors MCP](https://github.com/OctagonAI/octagon-investors-mcp)** - Investor profiles and investment strategies
- **[Octagon Funding Data MCP](https://github.com/OctagonAI/octagon-funding-data-mcp)** - Startup funding rounds and venture capital data

### Research Tools
- **[Octagon Deep Research MCP](https://github.com/OctagonAI/octagon-deep-research-mcp)** - Comprehensive research and web scraping capabilities

---

⭐ Star this repo if you find it helpful!

```

--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------

```dockerfile
FROM node:18-alpine

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm install --ignore-scripts

# Copy source code
COPY . .

# Build the application
RUN npm run build

# Run the server
CMD ["node", "dist/index.js"] 
```

--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist", "examples"]
} 
```

--------------------------------------------------------------------------------
/smithery.yaml:
--------------------------------------------------------------------------------

```yaml
startCommand:
  type: stdio
  configSchema:
    type: object
    required:
      - octagonApiKey
    properties:
      octagonApiKey:
        type: string
        description: Your Octagon API key (get a free one at https://app.octagonai.co/signup)
  commandFunction: |
    (config) => ({
      command: 'node',
      args: ['dist/index.js'],
      env: { OCTAGON_API_KEY: config.octagonApiKey }
    }) 
```

--------------------------------------------------------------------------------
/run-server.sh:
--------------------------------------------------------------------------------

```bash
#!/bin/bash

# Octagon MCP Server Run Script

echo "Starting Octagon MCP Server..."

# Check if the dist directory exists, if not, build the project
if [ ! -d "./dist" ]; then
    echo "Dist directory not found. Building project..."
    npm run build
fi

# Check if OCTAGON_API_KEY is set
if [ -z "$OCTAGON_API_KEY" ]; then
    # Try to load from .env file
    if [ -f ".env" ]; then
        export $(grep -v '^#' .env | xargs)
    fi
    
    # Check again if OCTAGON_API_KEY is set
    if [ -z "$OCTAGON_API_KEY" ]; then
        echo "Error: OCTAGON_API_KEY environment variable not set."
        echo "Please set your API key using: export OCTAGON_API_KEY=your_api_key"
        echo "Or create a .env file with OCTAGON_API_KEY=your_api_key"
        exit 1
    fi
fi

# Run the server
echo "Running server..."
node dist/index.js 
```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
{
  "name": "octagon-mcp",
  "version": "1.0.22",
  "description": "MCP server for Octagon API. Provides specialized AI agents for investment research of public and private markets.",
  "main": "dist/index.js",
  "type": "module",
  "bin": {
    "octagon-mcp": "dist/index.js"
  },
  "files": [
    "dist"
  ],
  "publishConfig": {
    "access": "public"
  },
  "scripts": {
    "build": "tsc && node -e \"require('fs').chmodSync('dist/index.js', '755')\"",
    "test": "echo \"No tests specified\"",
    "start": "node dist/index.js",
    "lint": "echo \"No linting configured\"",
    "format": "echo \"No formatting configured\"",
    "prepare": "npm run build",
    "release": "npm run build && npm publish"
  },
  "keywords": [
    "mcp",
    "octagon",
    "investment-research",
    "sec-filings",
    "earnings-transcripts",
    "financial-data",
    "market-data",
    "private-company-research"
  ],
  "author": "Octagon AI",
  "license": "MIT",
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.0.0",
    "dotenv": "^16.3.1",
    "openai": "^4.20.1",
    "zod": "^3.22.4"
  },
  "devDependencies": {
    "@types/node": "^20.10.0",
    "ts-node": "^10.9.2",
    "typescript": "^5.3.2"
  },
  "engines": {
    "node": ">=18.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/OctagonAI/octagon-mcp-server.git"
  },
  "bugs": {
    "url": "https://github.com/OctagonAI/octagon-mcp-server/issues"
  },
  "homepage": "https://docs.octagonagents.com"
}

```

--------------------------------------------------------------------------------
/install.sh:
--------------------------------------------------------------------------------

```bash
#!/bin/bash

# Octagon MCP Server Installation Script

echo "Installing Octagon MCP Server..."

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "Node.js is not installed. Please install Node.js before continuing."
    exit 1
fi

# Check if npm is installed
if ! command -v npm &> /dev/null; then
    echo "npm is not installed. Please install npm before continuing."
    exit 1
fi

# Install dependencies
echo "Installing dependencies..."
npm install

# Build the server
echo "Building the server..."
npm run build

# Create .env file if it doesn't exist
if [ ! -f .env ]; then
    echo "Creating .env file..."
    cp .env.example .env
    echo "Please edit the .env file and add your Octagon API key."
fi

echo "Installation complete!"
echo ""
echo "There are multiple ways to use the Octagon MCP Server:"
echo ""
echo "1. Run directly with your API key:"
echo "   env OCTAGON_API_KEY=your_octagon_api_key node ./dist/index.js"
echo ""
echo "2. Install globally and run with npx:"
echo "   npm install -g ."
echo "   env OCTAGON_API_KEY=your_octagon_api_key npx octagon-mcp"
echo ""
echo "3. To use with Claude Desktop, add the following to your claude_desktop_config.json:"
echo '{
  "mcpServers": {
    "octagon": {
      "command": "env",
      "args": ["OCTAGON_API_KEY=your_octagon_api_key", "npx", "-y", "octagon-mcp"]
    }
  }
}'
echo ""
echo "4. To use with Cursor, add a new MCP server with:"
echo "   - Name: octagon-mcp"
echo "   - Type: command"
echo "   - Command: env OCTAGON_API_KEY=your_octagon_api_key npx -y octagon-mcp" 
```

--------------------------------------------------------------------------------
/examples/typescript-client-example.ts:
--------------------------------------------------------------------------------

```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

async function main() {
  try {
    // Create a client
    const client = new Client({
      name: "octagon-client-example",
      version: "1.0.0",
    });

    // Connect to the server
    const transport = new StdioClientTransport({
      command: "node",
      args: ["../build/index.js"],  // Updated path to reflect the new location
    });
    await client.connect(transport);

    console.log("Connected to Octagon MCP server");

    // List available tools
    const toolsResult = await client.listTools();
    console.log("Available tools:");
    for (const tool of toolsResult.tools) {
      console.log(`- ${tool.name}: ${tool.description}`);
    }

    // Example: Query comprehensive market intelligence
    console.log("\nQuerying comprehensive market intelligence for Apple...");
    const marketResult = await client.callTool({
      name: "octagon-agent",
      arguments: {
        prompt: "Analyze Apple's latest 10-K filing and extract key financial metrics and risk factors",
      },
    });

    console.log("Market Intelligence Result:");
    console.log((marketResult as any).content[0].text);

    // Example: Deep research analysis
    console.log("\nPerforming deep research on AI market trends...");
    const researchResult = await client.callTool({
      name: "octagon-deep-research-agent",
      arguments: {
        prompt: "Research the financial impact of AI adoption on semiconductor companies' revenue and margins",
      },
    });

    console.log("Deep Research Analysis:");
    console.log((researchResult as any).content[0].text);

    // Example: Web scraping
    console.log("\nExtracting data from a website...");
    const scrapingResult = await client.callTool({
      name: "octagon-scraper-agent",
      arguments: {
        prompt: "Extract all data fields from zillow.com/san-francisco-ca/",
      },
    });

    console.log("Web Scraping Result:");
    console.log((scrapingResult as any).content[0].text);

    // Close the client
    await client.close();
  } catch (error) {
    console.error("Error:", error);
    process.exit(1);
  }
}

main(); 
```

--------------------------------------------------------------------------------
/examples/python-client-example.py:
--------------------------------------------------------------------------------

```python
#!/usr/bin/env python3
import asyncio
import os
from typing import Optional
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
    # Create server parameters for stdio connection
    server_params = StdioServerParameters(
        command="node",
        args=["../build/index.js"],  # Updated path to reflect the new location
        env=None
    )

    # Connect to the server
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Initialize the connection
            await session.initialize()
            print("Connected to Octagon MCP server")

            # List available tools
            tools = await session.list_tools()
            print("Available tools:")
            for tool in tools.tools:
                print(f"- {tool.name}: {tool.description}")

            # Example: Query comprehensive market intelligence
            print("\nQuerying comprehensive market intelligence for Apple...")
            market_result = await session.call_tool(
                "octagon-agent", 
                arguments={
                    "prompt": "Analyze Apple's latest 10-K filing and extract key financial metrics and risk factors"
                }
            )
            print("Market Intelligence Result:")
            print(market_result.content[0].text)

            # Example: Deep research analysis
            print("\nPerforming deep research on AI market trends...")
            research_result = await session.call_tool(
                "octagon-deep-research-agent",
                arguments={
                    "prompt": "Research the financial impact of AI adoption on semiconductor companies' revenue and margins"
                }
            )
            print("Deep Research Analysis:")
            print(research_result.content[0].text)

            # Example: Web scraping
            print("\nExtracting data from a website...")
            scraping_result = await session.call_tool(
                "octagon-scraper-agent",
                arguments={
                    "prompt": "Extract all data fields from zillow.com/san-francisco-ca/"
                }
            )
            print("Web Scraping Result:")
            print(scraping_result.content[0].text)

if __name__ == "__main__":
    asyncio.run(main()) 
```

--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------

```typescript
#!/usr/bin/env node

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import dotenv from "dotenv";
import { readFile } from "fs/promises";
import OpenAI from "openai";
import path from "path";
import { fileURLToPath } from "url";
import { z } from "zod";

// Get package.json info
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const packageJsonPath = path.join(__dirname, "..", "package.json");
const packageJsonContent = await readFile(packageJsonPath, "utf8");
const packageInfo = JSON.parse(packageJsonContent) as { name: string; version: string };

// Load environment variables
dotenv.config();

// Check for required environment variables
const OCTAGON_API_KEY = process.env.OCTAGON_API_KEY;
const OCTAGON_API_BASE_URL = process.env.OCTAGON_API_BASE_URL || "https://api.octagonagents.com/v1";

if (!OCTAGON_API_KEY) {
  console.error("Error: OCTAGON_API_KEY is not set in the environment variables");
  console.error("Please set the OCTAGON_API_KEY environment variable or use 'env OCTAGON_API_KEY=your_key npx -y octagon-mcp'");
  process.exit(1);
}

// Initialize OpenAI client with Octagon API
const octagonClient = new OpenAI({
  apiKey: OCTAGON_API_KEY,
  baseURL: OCTAGON_API_BASE_URL,
  defaultHeaders: {
    "User-Agent": `${packageInfo.name}/${packageInfo.version} (Node.js/${process.versions.node})`
  },
});

// Create MCP server
const server = new McpServer({
  name: packageInfo.name,
  version: packageInfo.version,
});

// Helper function to process streaming responses
async function processStreamingResponse(stream: any): Promise<string> {
  let fullResponse = "";
  let citations: any[] = [];

  try {
    // Process the streaming response
    for await (const chunk of stream) {
      // For Chat Completions API
      if (chunk.choices && chunk.choices[0]?.delta?.content) {
        fullResponse += chunk.choices[0].delta.content;

        // Check for citations in the final chunk
        if (chunk.choices[0]?.finish_reason === "stop" && chunk.choices[0]?.citations) {
          citations = chunk.choices[0].citations;
        }
      }

      // For Responses API
      if (chunk.type === "response.output_text.delta") {
        fullResponse += chunk.text?.delta || "";
      }
    }

    return fullResponse;
  } catch (error) {
    console.error("Error processing streaming response:", error);
    throw error;
  }
}

// Define a schema for the 'prompt' parameter that all tools will use
const promptSchema = z.object({
  prompt: z.string().describe("Your natural language query or request for the agent"),
});

type PromptParams = {
  prompt: string;
};

// Comprehensive Orchestration Agent
server.tool(
  "octagon-agent",
  "[COMPREHENSIVE MARKET INTELLIGENCE] Orchestrates all agents for comprehensive market intelligence analysis. Capabilities: Combines insights from SEC filings, earnings calls, financial metrics, stock data, institutional holdings, private company research, funding analysis, M&A transactions, investor intelligence, and debt analysis to provide holistic market intelligence. Best for: Complex research requiring multiple data sources and comprehensive analysis across public and private markets. Example queries: 'Retrieve year-over-year growth in key income-statement items for AAPL, limited to 5 records and filtered by period FY', 'Analyze the latest 10-K filing for AAPL and extract key financial metrics and risk factors', 'Retrieve the daily closing prices for AAPL over the last 30 days', 'Analyze AAPL's latest earnings call transcript and extract key insights about future guidance', 'Provide a comprehensive overview of Stripe, including its business model and key metrics', 'Retrieve the funding history for Stripe, including all rounds and investors'.",
  {
    prompt: z.string().describe("Your natural language query or request for the agent"),
  },
  async ({ prompt }: PromptParams) => {
    try {
      const response = await octagonClient.chat.completions.create({
        model: "octagon-agent",
        messages: [{ role: "user", content: prompt }],
        stream: true,
        metadata: { tool: "mcp" }
      });

      const result = await processStreamingResponse(response);
      return {
        content: [
          {
            type: "text",
            text: result,
          },
        ],
      };
    } catch (error) {
      console.error("Error calling Octagon orchestration agent:", error);
      return {
        isError: true,
        content: [
          {
            type: "text",
            text: `Error: Failed to process comprehensive market intelligence query. ${error}`,
          },
        ],
      };
    }
  }
);

// Web Scraper Agent
server.tool(
  "octagon-scraper-agent",
  "[PUBLIC & PRIVATE MARKET INTELLIGENCE] Specialized agent for financial data extraction from investor websites. Capabilities: Extract structured financial data from investor relations websites, tables, and online financial sources. Best for: Gathering financial data from websites that don't have accessible APIs. Example queries: 'Extract all data fields from zillow.com/san-francisco-ca/', 'Extract all data fields from www.carvana.com/cars/'.",
  {
    prompt: z.string().describe("Your natural language query or request for the agent"),
  },
  async ({ prompt }: PromptParams) => {
    try {
      const response = await octagonClient.chat.completions.create({
        model: "octagon-scraper-agent",
        messages: [{ role: "user", content: prompt }],
        stream: true,
        metadata: { tool: "mcp" }
      });

      const result = await processStreamingResponse(response);
      return {
        content: [
          {
            type: "text",
            text: result,
          },
        ],
      };
    } catch (error) {
      console.error("Error calling Scraper agent:", error);
      return {
        isError: true,
        content: [
          {
            type: "text",
            text: `Error: Failed to process web scraping query. ${error}`,
          },
        ],
      };
    }
  }
);

// Deep Research Agent
server.tool(
  "octagon-deep-research-agent",
  "[PUBLIC & PRIVATE MARKET INTELLIGENCE] A comprehensive agent that can utilize multiple sources for deep research analysis. Capabilities: Aggregate research across multiple data sources, synthesize information, and provide comprehensive investment research. Best for: Investment research questions requiring up-to-date aggregated information from the web. Example queries: 'Research the financial impact of Apple's privacy changes on digital advertising companies' revenue and margins', 'Analyze the competitive landscape in the cloud computing sector, focusing on AWS, Azure, and Google Cloud margin and growth trends', 'Investigate the factors driving electric vehicle adoption and their impact on battery supplier financials'.",
  {
    prompt: z.string().describe("Your natural language query or request for the agent"),
  },
  async ({ prompt }: PromptParams) => {
    try {
      const response = await octagonClient.chat.completions.create({
        model: "octagon-deep-research-agent",
        messages: [{ role: "user", content: prompt }],
        stream: true,
        metadata: { tool: "mcp" }
      });

      const result = await processStreamingResponse(response);
      return {
        content: [
          {
            type: "text",
            text: result,
          },
        ],
      };
    } catch (error) {
      console.error("Error calling Deep Research agent:", error);
      return {
        isError: true,
        content: [
          {
            type: "text",
            text: `Error: Failed to process deep research query. ${error}`,
          },
        ],
      };
    }
  }
);

// Start the server with stdio transport
async function main() {
  try {
    const transport = new StdioServerTransport();
    await server.connect(transport);
  } catch (error) {
    process.exit(1);
  }
}

main(); 

```