diff --git a/AGENTS.md b/AGENTS.md index 1c6dfc9..1752326 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,12 @@ This document helps agents work effectively with the DFlow MCP Server repository ## Project Overview -This is a Model Context Protocol (MCP) server that provides access to the Prediction Market Metadata API defined in `llms_dflow.json`. The server implements a complete JSON-RPC interface with 23 tools covering events, markets, trades, forecasts, live data, and analytics. +This is a Model Context Protocol (MCP) server providing access to prediction market data from two platforms: + +1. **DFlow/Kalshi** — CFTC-regulated centralized exchange (order book, USD settlement) +2. **Baozi.bet** — Decentralized pari-mutuel markets on Solana (pool-based, SOL settlement) + +**35 total tools** across both platforms. ## Essential Commands @@ -40,7 +45,7 @@ bun run test ``` dflow-mcp/ ├── src/ -│ └── index.ts # Main MCP server implementation +│ └── index.ts # Main MCP server (DFlow + Baozi tools) ├── tests/ │ └── server.test.ts # TypeScript test suite ├── .github/workflows/ @@ -48,8 +53,8 @@ dflow-mcp/ ├── package.json # Dependencies and scripts ├── tsconfig.json # TypeScript configuration ├── README.md # User documentation -├── llms_dflow.json # API specification (source of truth) -├── AGENTS.md # This file (agent documentation) +├── llms_dflow.json # DFlow API specification +├── AGENTS.md # This file └── test-server.sh # Quick server validation script ``` @@ -57,27 +62,25 @@ dflow-mcp/ ### Main Server (`src/index.ts`) -- **DFlowAPIClient**: HTTP client for API communication with timeout handling +- **DFlowAPIClient**: HTTP client for DFlow/Kalshi API (GET + POST, timeout handling) +- **BaoziAPIClient**: HTTP client for Baozi.bet API (GET, handles JSON + markdown responses) - **Server Setup**: MCP server configuration and initialization -- **Tool Definitions**: 23 MCP tools mapped from OpenAPI specification +- **Tool Definitions**: 35 MCP tools (23 DFlow + 12 Baozi) +- **Prompts**: 4 analysis prompts (market trends, event comparison, Baozi analysis, cross-platform) +- **Resources**: 6 data resources (3 DFlow + 3 Baozi) - **Request Handling**: JSON-RPC request routing and response formatting -### Key Components - -1. **API Client**: Handles HTTP requests to `https://api.llm.dflow.org` -2. **Tool Registry**: Maps OpenAPI endpoints to MCP tools -3. **Type Safety**: TypeScript interfaces for all request/response types -4. **Error Handling**: Comprehensive error catching and MCP-formatted responses - ## Tool Categories -### Event Management (4 tools) +### DFlow / Kalshi Tools (23) + +#### Event Management (4 tools) - `get_event` - Single event by ticker - `get_events` - Paginated event list with filtering - `search_events` - Search by title/ticker - `get_live_data_by_event` - Live data for event -### Market Operations (6 tools) +#### Market Operations (6 tools) - `get_market` - Market by ticker - `get_market_by_mint` - Market by mint address - `get_markets` - Paginated markets with filters @@ -85,179 +88,103 @@ dflow-mcp/ - `get_market_candlesticks` - OHLC data for market - `get_market_candlesticks_by_mint` - Candlesticks by mint -### Trade & Analytics (4 tools) +#### Trade & Analytics (4 tools) - `get_trades` - Trades across markets - `get_trades_by_mint` - Trades for specific market - `get_forecast_percentile_history` - Forecast analytics - `get_forecast_percentile_history_by_mint` - Forecast by mint -### Live Data & Series (5 tools) +#### Live Data & Series (5 tools) - `get_live_data` - Live data for milestones - `get_live_data_by_mint` - Live data by mint - `get_series` - All series templates - `get_series_by_ticker` - Series by ticker - `get_event_candlesticks` - Event candlesticks -### Utilities (4 tools) +#### Utilities (4 tools) - `get_outcome_mints` - Outcome mint addresses - `filter_outcome_mints` - Filter addresses to outcome mints - `get_tags_by_categories` - Category-tag mapping - `get_filters_by_sports` - Sports filtering options -## API Reference - -### Base Configuration -- **API URL**: `https://api.llm.dflow.org` -- **Timeout**: 30 seconds (configurable) -- **Transport**: MCP stdio (JSON-RPC 2.0) - -### Request/Response Pattern -- All tools accept JSON-RPC requests with validated input schemas -- Responses are formatted as MCP text content with JSON strings -- Errors return formatted error messages with context - -### Authentication -- Current API implementation does not require authentication -- If auth is added later, configure in DFlowAPIClient headers - -## Development Patterns - -### Adding New Tools - -1. **Define Tool Schema**: Add to TOOLS array in server setup -2. **Implement Handler**: Add case in main switch statement -3. **Map API Endpoint**: Use DFlowAPIClient methods -4. **Validate Parameters**: MCP handles schema validation - -Example pattern: -```typescript -{ - name: 'new_endpoint', - description: 'Description of the tool', - inputSchema: { - type: 'object', - properties: { - param1: { type: 'string', description: 'Param description' } - }, - required: ['param1'] - } -} -``` - -### Error Handling +### Baozi.bet Solana Tools (12) -- Use try-catch blocks for API calls -- Format errors as MCP text content with `isError: true` -- Include context about which tool failed -- Preserve original error messages for debugging +#### Market Discovery (3 tools) +- `baozi_get_markets` - List markets with status/limit/offset filtering +- `baozi_get_market` - Single market by Solana public key +- `baozi_get_agent_markets` - Agent-optimized list (filter by betting_open) -### Type Safety +#### Bet Analysis (1 tool) +- `baozi_get_quote` - Calculate payout, odds, fees for a potential bet -- All tool parameters should be typed in inputSchema -- Use type guards for complex parameter validation -- Maintain consistent naming between API and tools +#### Portfolio (1 tool) +- `baozi_get_positions` - All positions for a Solana wallet (binary + race) -## Code Style Conventions +#### Metadata (1 tool) +- `baozi_get_market_metadata` - Batch fetch descriptions, rules, images, categories -### TypeScript -- Use strict TypeScript settings (configured in tsconfig.json) -- Import statements at top, grouped by type -- Explicit return types for public functions -- Use `const` by default, `let` only when necessary +#### Agent Ecosystem (1 tool) +- `baozi_get_agent_info` - Registered agents, MCP details, fees, registration guide -### Naming -- **Tool names**: snake_case with descriptive names -- **Parameters**: snake_case matching API specification -- **Variables**: camelCase for local variables -- **Functions**: camelCase with descriptive verbs +#### Oracle (1 tool) +- `baozi_get_oracle_proofs` - Resolution proofs with evidence and rationale -### Documentation -- Tool descriptions should explain purpose and expected response -- Parameter descriptions should include units and constraints -- Include examples for complex tools in README +#### Documentation (3 tools) +- `baozi_get_skill_docs` - Complete protocol docs (69 MCP tools reference) +- `baozi_get_guardrails` - Pari-mutuel market creation rules v7.2 +- `baozi_get_program_idl` - Anchor IDL for direct on-chain RPC -## Testing Approach +#### Social (1 tool) +- `baozi_get_share_card` - Generate 1200x630 PNG share card URL -### Manual Testing -```bash -# Quick validation -./test-server.sh - -# Direct tool testing -echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_events","arguments":{}}}' | bun run src/index.ts -``` - -### Integration Testing -- Test MCP protocol compliance -- Validate JSON schemas -- Test error handling scenarios -- Verify API endpoint mapping +## API Reference -## Common Issues & Solutions +### DFlow Configuration +- **API URL**: `https://prediction-markets-api.dflow.net` +- **Auth**: None required +- **Timeout**: 30 seconds (configurable) -### Server Not Responding -- Check TypeScript compilation with `bun run tsc --noEmit` -- Ensure all dependencies installed with `bun install` -- Verify stdio transport is working (common in CI environments) +### Baozi Configuration +- **API URL**: `https://baozi.bet` +- **Auth**: None required for read operations +- **Program**: `FWyTPzm5cfJwRKzfkscxozatSxF6Qu78JQovQUwKPruJ` (Solana mainnet) +- **Full MCP**: `@baozi.bet/mcp-server` (69 tools, read+write, requires Solana wallet) + +### Baozi API Endpoints + +| Endpoint | Method | Returns | +|----------|--------|---------| +| `/api/v4/markets` | GET | Markets list (JSON) | +| `/api/v4/market/:key` | GET | Single market (JSON) | +| `/api/v4/agent/markets` | GET | Agent-optimized markets (JSON) | +| `/api/v4/quote` | GET | Bet payout calculation (JSON) | +| `/api/v4/positions/:wallet` | GET | Wallet positions (JSON) | +| `/api/markets/metadata` | GET | Off-chain metadata batch (JSON) | +| `/api/v4/agents` | GET | Agent ecosystem info (JSON) | +| `/api/agents/proofs` | GET | Oracle resolution proofs (JSON) | +| `/api/skill` | GET | Protocol documentation (markdown) | +| `/api/pari-mutuel-guardrails` | GET | Market creation rules (markdown) | +| `/api/mcp/idl` | GET | Program IDL (JSON) | +| `/api/share/card` | GET | Share card image (PNG) | -### Tool Parameter Validation -- MCP handles schema validation automatically -- Missing required parameters return validation errors -- Invalid types are caught before API calls +## Development Patterns -### API Rate Limits -- Current API doesn't have documented rate limits -- Monitor response headers for rate limit information -- Implement exponential backoff if needed +### Adding New Tools -## Deployment Considerations +1. **Define Tool Schema**: Add to TOOLS array with `baozi_` prefix for Baozi tools +2. **Implement Handler**: Add case in main switch statement +3. **Map API Endpoint**: Use `baoziClient.get()` for Baozi or `apiClient.get()` for DFlow +4. **Validate Parameters**: MCP handles schema validation -### Development -- Use `bun run dev` for hot reloading during development -- Server communicates via stdio, not HTTP server -- Test with actual MCP client (Claude Desktop, Cursor) - -### Production -- Build with `bun run build` for optimized bundle -- Use `bun start` for production execution -- Monitor server startup and connection handling - -### CI/CD -- GitHub Actions workflow in `.github/workflows/test.yml` -- Tests compilation and basic server functionality -- Can add integration tests with mock API responses - -## API Specification Source - -The API specification in `llms_dflow.json` is the single source of truth: -- OpenAPI 3.0 format -- Complete with schemas, parameters, and responses -- All tools derived from this specification -- Update tools when API specification changes - -## Future Enhancements - -### Potential Additions -- WebSocket support for real-time data -- Caching layer for frequently accessed data -- Pagination helpers for large datasets -- Rate limiting and retry logic -- Authentication token management - -### Scaling Considerations -- Connection pooling for high-volume usage -- Response compression for large payloads -- Request deduplication for concurrent calls -- Health check endpoints for monitoring +### Naming Convention +- DFlow tools: `get_*` (existing pattern) +- Baozi tools: `baozi_*` prefix (platform-namespaced) ## Agent-Specific Tips -When working with this repository: - 1. **Always test after changes**: Run `./test-server.sh` to validate -2. **Check API specification**: Reference `llms_dflow.json` for endpoint details +2. **Check API specification**: `llms_dflow.json` for DFlow, `baozi.bet/skill` for Baozi 3. **Maintain type safety**: Use TypeScript strict mode 4. **Follow MCP patterns**: Standard JSON-RPC 2.0 with stdio transport 5. **Document new tools**: Update README.md and AGENTS.md when adding tools - -The server is designed to be a direct, type-safe wrapper around the Prediction Market API with comprehensive MCP protocol support. \ No newline at end of file +6. **Platform prefix**: All Baozi tools use `baozi_` prefix to avoid naming conflicts diff --git a/CLAUDE.md b/CLAUDE.md index 90f1aae..9460181 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,9 +4,16 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -This is an MCP (Model Context Protocol) server that provides access to the Prediction Market Metadata API. The server wraps the REST API defined in `llms_dflow.json` and exposes it as MCP tools for use with Claude Desktop, Cursor, and other MCP clients. +This is an MCP (Model Context Protocol) server that provides access to prediction market data from **two platforms**: -**Base API URL**: `https://prediction-markets-api.dflow.net` +1. **DFlow/Kalshi** — CFTC-regulated centralized prediction market (order book model) +2. **Baozi.bet** — Decentralized pari-mutuel prediction markets on Solana + +The server wraps both REST APIs and exposes them as MCP tools for use with Claude Desktop, Cursor, and other MCP clients. **35 total tools** (23 DFlow + 12 Baozi). + +**Base API URLs**: +- DFlow: `https://prediction-markets-api.dflow.net` +- Baozi: `https://baozi.bet` ## Commands @@ -34,106 +41,71 @@ bun run src/index.ts ### Single-File MCP Server -The entire server implementation is contained in `src/index.ts`. This is intentional for simplicity - the server is a thin wrapper around the external API. +The entire server implementation is contained in `src/index.ts`. This is intentional for simplicity — the server is a thin wrapper around external APIs. **Key components:** -1. **DFlowAPIClient** (lines 23-85): HTTP client that handles all API communication +1. **DFlowAPIClient**: HTTP client for DFlow/Kalshi API communication - Implements request timeout handling (30s default) - Constructs URLs with query parameters - Handles GET and POST requests - - Returns parsed JSON responses -2. **TOOLS array** (lines 103-696): Complete tool definitions - - Each tool maps to one API endpoint - - Tool definitions include JSON schemas for parameter validation - - Organized by endpoint category (events, markets, trades, forecasts, candlesticks, live data, series, utilities) +2. **BaoziAPIClient**: HTTP client for Baozi.bet API communication + - Same timeout/error handling pattern as DFlowAPIClient + - Handles both JSON and text/markdown responses + - Connects to Solana prediction market endpoints -3. **Request handlers** (lines 698-849): - - `ListToolsRequestSchema`: Returns all available tools - - `CallToolRequestSchema`: Routes tool calls to appropriate API endpoints using a large switch statement - - Error handling returns descriptive messages +3. **TOOLS array**: Complete tool definitions (35 tools) + - DFlow tools (23): Events, markets, trades, forecasts, candlesticks, live data, series, utilities + - Baozi tools (12): Markets, quotes, positions, metadata, oracle proofs, docs, share cards -### API Endpoint Categories +4. **Request handlers**: + - `ListToolsRequestSchema`: Returns all 35 tools + - `CallToolRequestSchema`: Routes tool calls via switch statement + - `ListPromptsRequestSchema`: 4 prompts (2 DFlow + 2 Baozi/cross-platform) + - `ListResourcesRequestSchema`: 6 resources (3 DFlow + 3 Baozi) + - Error handling returns descriptive messages -The server exposes 25 tools across 8 categories: +### Baozi.bet Tool Categories -- **Events**: Get individual events, paginated event lists, search events -- **Markets**: Get markets by ticker or mint address, batch queries -- **Trades**: Query trade history with filtering and pagination -- **Forecasts**: Historical forecast percentile data -- **Candlesticks**: OHLC data for events and markets -- **Live Data**: Real-time milestone information -- **Series**: Series templates and metadata -- **Utilities**: Outcome mints, filtering, tags, and search +| Category | Tools | Endpoint Pattern | +|----------|-------|-----------------| +| Market Discovery | `baozi_get_markets`, `baozi_get_market`, `baozi_get_agent_markets` | `/api/v4/markets`, `/api/v4/market/:key`, `/api/v4/agent/markets` | +| Bet Analysis | `baozi_get_quote` | `/api/v4/quote?market=&side=&amount=` | +| Portfolio | `baozi_get_positions` | `/api/v4/positions/:wallet` | +| Metadata | `baozi_get_market_metadata` | `/api/markets/metadata?marketIds=` | +| Agent Ecosystem | `baozi_get_agent_info` | `/api/v4/agents` | +| Oracle | `baozi_get_oracle_proofs` | `/api/agents/proofs` | +| Documentation | `baozi_get_skill_docs`, `baozi_get_guardrails`, `baozi_get_program_idl` | `/api/skill`, `/api/pari-mutuel-guardrails`, `/api/mcp/idl` | +| Social | `baozi_get_share_card` | `/api/share/card?market=` (returns URL) | ### MCP Transport -The server uses **stdio transport** (line 853), which is the standard for MCP servers. This means: +The server uses **stdio transport**, the standard for MCP servers: - Communication happens over stdin/stdout - The server must be launched as a subprocess by the MCP client - No HTTP server or network configuration needed -## Configuration Files - -- **package.json**: Dependencies include `@modelcontextprotocol/sdk` for MCP protocol implementation -- **tsconfig.json**: Standard TypeScript config targeting ES2022 with ESNext modules and bundler resolution -- **llms_dflow.json**: OpenAPI specification for the underlying REST API (not used at runtime, serves as documentation) -- **bun.lock**: Bun's lockfile (not bun.lockb, this is a text-based lock format) -- **.gitignore**: Standard Node.js gitignore that excludes node_modules, dist, logs, and environment files - ## Tool Implementation Pattern When adding or modifying tools, follow this pattern: 1. Add tool definition to `TOOLS` array with name, description, and `inputSchema` 2. Add corresponding case to the switch statement in the `CallToolRequestSchema` handler -3. Use `apiClient.get()` or `apiClient.post()` to make the API request -4. Extract path parameters from args and pass remaining args as query params or request body - -Example: -```typescript -// Tool definition -{ - name: 'get_event', - description: 'Get a single event by ticker', - inputSchema: { - type: 'object', - properties: { - event_id: { type: 'string', description: 'Event ticker' }, - withNestedMarkets: { type: 'boolean', description: 'Include nested markets' } - }, - required: ['event_id'] - } -} - -// Handler implementation -case 'get_event': - result = await apiClient.get(`/api/v1/event/${args.event_id}`, { - withNestedMarkets: args.withNestedMarkets, - }); - break; -``` +3. Use `apiClient.get()` for DFlow or `baoziClient.get()` for Baozi +4. Extract path parameters from args and pass remaining args as query params -## Testing the Server +## Configuration -To test the server manually with MCP client configuration (e.g., Claude Desktop): - -```json -{ - "mcpServers": { - "dflow-mcp": { - "command": "bun", - "args": ["run", "/absolute/path/to/dflow-mcp/src/index.ts"] - } - } -} -``` +Smithery config schema supports: +- `apiUrl`: DFlow API base URL (default: `https://prediction-markets-api.dflow.net`) +- `baoziApiUrl`: Baozi API base URL (default: `https://baozi.bet`) +- `requestTimeout`: Timeout in ms (default: 30000) ## Key Technical Details - **Runtime**: Designed for Bun but compatible with Node.js 18+ - **MCP SDK Version**: `@modelcontextprotocol/sdk` ^0.5.0 -- **Request Timeout**: 30 seconds (configurable via `DEFAULT_TIMEOUT`) -- **Error Handling**: HTTP errors and timeouts are caught and returned as MCP error responses -- **JSON Serialization**: Handles BigInt values by converting to strings +- **Request Timeout**: 30 seconds (configurable) +- **Baozi Program ID**: `FWyTPzm5cfJwRKzfkscxozatSxF6Qu78JQovQUwKPruJ` (Solana mainnet) +- **Baozi MCP Server**: `@baozi.bet/mcp-server` (69 tools for full read+write operations) diff --git a/README.md b/README.md index 4cab59b..8a62b25 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,21 @@ -# DFlow MCP Server +# DFlow MCP Server — Multi-Platform Prediction Markets [![smithery badge](https://smithery.ai/badge/@openSVM/dflow-mcp)](https://smithery.ai/server/@openSVM/dflow-mcp) -Access [Kalshi](https://kalshi.com) prediction market data - the first CFTC-regulated exchange for trading on real-world events. Built by [OpenSVM](https://osvm.ai). 23 tools for events, markets, trades, forecasts, candlesticks and live data. +**35 tools** for comprehensive prediction market coverage across centralized and decentralized platforms: -**Demo:** [https://dflow.opensvm.com](https://dflow.opensvm.com) +| Platform | Type | Markets | Tools | Settlement | +|----------|------|---------|-------|------------| +| [**Kalshi**](https://kalshi.com) via DFlow | CeFi (CFTC-regulated) | Order book | 23 | USD | +| [**Baozi.bet**](https://baozi.bet) | DeFi (Solana) | Pari-mutuel pools | 12 | SOL | -## Features +One MCP server. Two prediction market ecosystems. Full cross-platform analysis. + +**Demo:** [https://dflow.opensvm.com](https://dflow.opensvm.com) | **Baozi:** [https://baozi.bet](https://baozi.bet) -This MCP server provides access to the complete Prediction Market Metadata API including: +## Features +### DFlow / Kalshi (Centralized) - **Event Management**: Get events, search events, retrieve event metadata - **Market Data**: Market information, batch queries, market lookups by mint - **Trading Data**: Trade history, trades by market, pagination support @@ -19,25 +25,28 @@ This MCP server provides access to the complete Prediction Market Metadata API i - **Series Information**: Series templates, categories, and metadata - **Utility Functions**: Outcome mint queries, filtering, and search capability +### Baozi.bet (Decentralized — Solana) +- **Market Discovery**: Browse active pari-mutuel markets (binary Yes/No + multi-outcome race markets) +- **Real-Time Odds**: Live pool sizes and implied probabilities that shift with every bet +- **Bet Quoting**: Calculate exact payouts, fees, and odds before placing a bet +- **Portfolio Tracking**: View all positions for any Solana wallet with P&L data +- **Oracle Proofs**: Transparent resolution evidence from the "Grandma Mei" oracle system +- **Agent Ecosystem**: 69 MCP tools via dedicated `@baozi.bet/mcp-server`, agent registration, affiliate system +- **Share Cards**: Generate social media share images (1200x630 PNG) for any market +- **Protocol Docs**: Full on-chain program IDL, PDA seeds, and integration guides + ## Installation ### Method 1: Install via Smithery (Recommended) -The easiest way to install this MCP server is through [Smithery](https://smithery.ai): - ```bash npx @smithery/cli install dflow-mcp-server --client claude ``` -This will automatically configure the server for use with Claude Desktop. - ### Method 2: Manual Installation -#### Prerequisites -- [Bun](https://bun.sh/) (recommended) or Node.js 18+ - -#### Install Dependencies ```bash +# Prerequisites: Bun (recommended) or Node.js 18+ bun install ``` @@ -52,17 +61,11 @@ bun run dev # Production mode bun start -# Or directly with Bun +# Or directly bun run src/index.ts ``` -The server uses stdio transport for MCP communication, which is the standard for MCP clients. - -### Integration with MCP Clients - -#### Claude Desktop - -If you installed via Smithery, the configuration is automatic. For manual setup, add this to your Claude Desktop config: +### Claude Desktop Configuration ```json { @@ -75,52 +78,75 @@ If you installed via Smithery, the configuration is automatic. For manual setup, } ``` -#### Other MCP Clients - -This server is compatible with any MCP client (Cursor, Continue, etc.). Use the same configuration format as above. +Compatible with any MCP client: Claude Desktop, Claude Code, Cursor, Continue, and more. ## Available Tools -### Event Tools -- `get_event` - Get a single event by ticker -- `get_events` - Get paginated list of all events - -### Market Tools -- `get_market` - Get market details by ticker -- `get_market_by_mint` - Get market by mint address -- `get_markets` - Get paginated list of markets -- `get_markets_batch` - Get multiple markets (up to 100) - -### Trade Tools -- `get_trades` - Get trades across markets -- `get_trades_by_mint` - Get trades for specific market - -### Analytics Tools -- `get_forecast_percentile_history` - Get forecast history -- `get_forecast_percentile_history_by_mint` - Forecast history by mint -- `get_event_candlesticks` - Event candlestick data -- `get_market_candlesticks` - Market candlestick data -- `get_market_candlesticks_by_mint` - Candlesticks by mint - -### Live Data Tools -- `get_live_data` - Get live data for milestones -- `get_live_data_by_event` - Live data for event -- `get_live_data_by_mint` - Live data by mint - -### Series Tools -- `get_series` - Get all series templates -- `get_series_by_ticker` - Get specific series - -### Utility Tools -- `get_outcome_mints` - Get outcome mint addresses -- `filter_outcome_mints` - Filter addresses to outcome mints -- `get_tags_by_categories` - Get category-tag mapping -- `get_filters_by_sports` - Get sports filtering options -- `search_events` - Search events by title/ticker +### DFlow / Kalshi Tools (23) + +#### Events +| Tool | Description | +|------|-------------| +| `get_event` | Get a single event by ticker | +| `get_events` | Get paginated list of all events | +| `search_events` | Search events by title/ticker | + +#### Markets +| Tool | Description | +|------|-------------| +| `get_market` | Get market details by ticker | +| `get_market_by_mint` | Get market by mint address | +| `get_markets` | Get paginated list of markets | +| `get_markets_batch` | Get multiple markets (up to 100) | + +#### Trading & Analytics +| Tool | Description | +|------|-------------| +| `get_trades` | Get trades across markets | +| `get_trades_by_mint` | Get trades for specific market | +| `get_forecast_percentile_history` | Get forecast history | +| `get_forecast_percentile_history_by_mint` | Forecast history by mint | +| `get_event_candlesticks` | Event candlestick data | +| `get_market_candlesticks` | Market candlestick data | +| `get_market_candlesticks_by_mint` | Candlesticks by mint | + +#### Live Data & Series +| Tool | Description | +|------|-------------| +| `get_live_data` | Get live data for milestones | +| `get_live_data_by_event` | Live data for event | +| `get_live_data_by_mint` | Live data by mint | +| `get_series` | Get all series templates | +| `get_series_by_ticker` | Get specific series | + +#### Utilities +| Tool | Description | +|------|-------------| +| `get_outcome_mints` | Get outcome mint addresses | +| `filter_outcome_mints` | Filter addresses to outcome mints | +| `get_tags_by_categories` | Get category-tag mapping | +| `get_filters_by_sports` | Get sports filtering options | + +### Baozi.bet Solana Tools (12) + +| Tool | Description | +|------|-------------| +| `baozi_get_markets` | List active markets with odds, pools, and closing times | +| `baozi_get_market` | Get detailed market info by Solana public key | +| `baozi_get_agent_markets` | Agent-optimized market list (filter by betting status) | +| `baozi_get_quote` | Calculate payout/odds for a potential bet before placing it | +| `baozi_get_positions` | Get all positions for a Solana wallet | +| `baozi_get_market_metadata` | Batch fetch off-chain metadata (descriptions, rules, images) | +| `baozi_get_agent_info` | Agent Kitchen info — registered agents, MCP tools, fees | +| `baozi_get_oracle_proofs` | Oracle resolution proofs with evidence and rationale | +| `baozi_get_skill_docs` | Complete protocol documentation (69 MCP tools reference) | +| `baozi_get_guardrails` | Pari-mutuel market creation rules v7.2 | +| `baozi_get_program_idl` | Anchor IDL for direct on-chain interaction | +| `baozi_get_share_card` | Generate 1200x630 PNG share card for any market | ## Example Tool Calls -### Get a specific event +### DFlow: Get a specific event ```json { "tool": "get_event", @@ -131,96 +157,126 @@ This server is compatible with any MCP client (Cursor, Continue, etc.). Use the } ``` -### Get market by mint address +### Baozi: List active Solana markets ```json { - "tool": "get_market_by_mint", + "tool": "baozi_get_markets", "arguments": { - "mint_address": "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM" + "status": "Active", + "limit": 20 } } ``` -### Get forecast history +### Baozi: Calculate bet payout before betting ```json { - "tool": "get_forecast_percentile_history", + "tool": "baozi_get_quote", "arguments": { - "series_ticker": "US-PRESIDENT", - "event_id": "US-PRESIDENT-2024", - "percentiles": "25,50,75", - "startTs": 1704067200, - "endTs": 1706745600, - "periodInterval": 3600 + "market": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU", + "side": "Yes", + "amount": 1.0 } } ``` -### Search events +### Baozi: Check wallet portfolio ```json { - "tool": "search_events", + "tool": "baozi_get_positions", "arguments": { - "q": "election", - "limit": 10, - "sort": "volume", - "order": "desc" + "wallet": "YourSolanaWalletAddress" } } ``` -## Development - -### Project Structure -``` -dflow-mcp/ -├── src/ -│ └── index.ts # Main server implementation -├── package.json # Dependencies and scripts -├── tsconfig.json # TypeScript configuration -├── llms_dflow.json # API specification -└── README.md # This file +### Baozi: Get oracle resolution proof +```json +{ + "tool": "baozi_get_oracle_proofs", + "arguments": { + "layer": "official" + } +} ``` -### Building -```bash -bun run build -``` +## Prompts -### Testing -```bash -bun run test -``` +| Prompt | Description | +|--------|-------------| +| `analyze_market_trends` | Analyze DFlow market trends (volume, liquidity, price movements) | +| `compare_events` | Compare multiple DFlow events side-by-side | +| `baozi_market_analysis` | Find best Baozi.bet opportunities (odds, pools, timing) | +| `cross_platform_comparison` | Compare the same topics across Kalshi and Baozi.bet | -## API Details +## Resources -The server implements the complete REST API defined in `llms_dflow.json` with the following base URL: +| URI | Description | +|-----|-------------| +| `dflow://api/events` | Live DFlow prediction market events | +| `dflow://api/markets` | Active DFlow markets | +| `dflow://api/docs` | DFlow API documentation | +| `baozi://markets` | Active Baozi.bet Solana markets | +| `baozi://agents` | Baozi agent ecosystem info | +| `baozi://docs` | Complete Baozi protocol documentation | -``` -https://prediction-markets-api.dflow.net -``` +## Baozi.bet Platform Overview -All tools include comprehensive parameter validation and type definitions. Error handling returns informative messages for debugging. +[Baozi.bet](https://baozi.bet) is a decentralized prediction market protocol on Solana: -## Publishing to Smithery +- **Pari-mutuel pools** — Odds shift dynamically with every bet (no order book needed) +- **SOL-native** — Bet and win in SOL, no USDC or wrapped tokens +- **3 market layers** — Official (curated), Labs (community-created), Private (invite-only) +- **AI agent-first** — 69 MCP tools via `@baozi.bet/mcp-server`, agent registration, affiliate commissions +- **On-chain oracle** — "Grandma Mei" oracle with transparent resolution proofs and 6-hour dispute window +- **$BAOZI token** — Revenue sharing with stakers from protocol fees +- **Program:** `FWyTPzm5cfJwRKzfkscxozatSxF6Qu78JQovQUwKPruJ` (Solana mainnet) -This server is configured for publication on [Smithery](https://smithery.ai), the MCP server registry. +### Fee Structure -### Configuration Files +| Layer | Platform Fee | Creation Fee | +|-------|-------------|--------------| +| Official | 2.5% | 0.01 SOL | +| Labs | 3.0% | 0.01 SOL | +| Private | 2.0% | 0.01 SOL | -- `smithery.yaml` - Defines the runtime (TypeScript) and target (local) -- `package.json` - Includes module entry point and Smithery CLI scripts +### For AI Agents -### To Publish +Agents can earn affiliate commissions and create Lab markets. Install the full MCP server for write operations: -1. Ensure your code is pushed to a public GitHub repository -2. Visit [smithery.ai/new](https://smithery.ai/new) -3. Connect your GitHub repository -4. Smithery will automatically detect the `smithery.yaml` configuration +```bash +npm install -g @baozi.bet/mcp-server +# or +npx @baozi.bet/mcp-server +``` + +Learn more: [baozi.bet/agents](https://baozi.bet/agents) | [baozi.bet/skill](https://baozi.bet/skill) + +## Development + +### Project Structure +``` +dflow-mcp/ +├── src/ +│ └── index.ts # Main server (DFlow + Baozi tools) +├── package.json # Dependencies and scripts +├── tsconfig.json # TypeScript configuration +├── llms_dflow.json # DFlow API specification +└── README.md # This file +``` + +### API Base URLs + +| Platform | URL | +|----------|-----| +| DFlow | `https://prediction-markets-api.dflow.net` | +| Baozi.bet | `https://baozi.bet` | + +### Building & Testing -Once published, users can install your server with: ```bash -npx @smithery/cli install dflow-mcp-server --client claude +bun run build +bun run test ``` ## License @@ -229,4 +285,4 @@ MIT License - See LICENSE file for details. --- -**OpenSVM × Kalshi × DFlow** \ No newline at end of file +**OpenSVM x Kalshi x DFlow x Baozi.bet** diff --git a/package.json b/package.json index c95c863..e9d1662 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@openSVM/dflow-mcp", - "version": "1.0.0", - "description": "MCP Server for Prediction Market Metadata API - Access comprehensive prediction market data through 24 specialized tools", + "version": "1.1.0", + "description": "MCP Server for Prediction Markets — 35 tools across DFlow/Kalshi (CeFi) and Baozi.bet (DeFi/Solana) for events, markets, trades, odds, oracle proofs, and cross-platform analysis", "type": "module", "module": "src/index.ts", "displayName": "DFlow MCP Server", @@ -16,10 +16,16 @@ "model-context-protocol", "prediction-markets", "dflow", + "baozi", + "kalshi", + "solana", + "defi", + "pari-mutuel", "api", "trading", "analytics", - "solana" + "oracle", + "ai-agents" ], "author": "openSVM", "license": "MIT", diff --git a/src/index.ts b/src/index.ts index 8e4ed86..8fca0d4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,12 @@ #!/usr/bin/env bun /** - * MCP Server for Prediction Market Metadata API + * MCP Server for Prediction Markets — DFlow (Kalshi) + Baozi (Solana) * - * This server implements a Model Context Protocol (MCP) interface to the - * Prediction Market Metadata API defined in llms_dflow.json. + * Multi-platform prediction market MCP server combining: + * - DFlow/Kalshi: CFTC-regulated centralized exchange (23 tools) + * - Baozi.bet: Decentralized pari-mutuel markets on Solana (12 tools) + * + * 35 total tools for comprehensive prediction market coverage. */ import { Server } from '@modelcontextprotocol/sdk/server/index.js'; @@ -27,8 +30,11 @@ import { z } from 'zod'; */ export const configSchema = z.object({ apiUrl: z.string() - .describe('Base URL for the Prediction Market Metadata API') + .describe('Base URL for the DFlow Prediction Market API') .default('https://prediction-markets-api.dflow.net'), + baoziApiUrl: z.string() + .describe('Base URL for the Baozi.bet Solana prediction market API') + .default('https://baozi.bet'), requestTimeout: z.number() .describe('Timeout for API requests in milliseconds') .default(30000), @@ -36,6 +42,7 @@ export const configSchema = z.object({ // API Configuration const BASE_URL = 'https://prediction-markets-api.dflow.net'; +const BAOZI_BASE_URL = 'https://baozi.bet'; const DEFAULT_TIMEOUT = 30000; // 30 seconds class DFlowAPIClient { @@ -102,9 +109,64 @@ class DFlowAPIClient { } } +class BaoziAPIClient { + readonly baseUrl: string; + private timeout: number; + + constructor(baseUrl: string = BAOZI_BASE_URL, timeout: number = DEFAULT_TIMEOUT) { + this.baseUrl = baseUrl.replace(/\/$/, ''); + this.timeout = timeout; + } + + private makeUrl(path: string): string { + return `${this.baseUrl}${path.startsWith('/') ? path : '/' + path}`; + } + + async get(path: string, params?: Record): Promise { + const url = new URL(this.makeUrl(path)); + if (params) { + Object.entries(params).forEach(([key, value]) => { + if (value !== undefined && value !== null) { + url.searchParams.append(key, String(value)); + } + }); + } + + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), this.timeout); + + try { + const response = await fetch(url.toString(), { + method: 'GET', + headers: { 'Accept': 'application/json, text/markdown, text/plain' }, + signal: controller.signal, + }); + + clearTimeout(timeoutId); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${await response.text()}`); + } + + const contentType = response.headers.get('content-type') || ''; + if (contentType.includes('application/json')) { + return await response.json(); + } + return { content: await response.text(), contentType }; + } catch (error) { + clearTimeout(timeoutId); + if (error instanceof Error && error.name === 'AbortError') { + throw new Error('Request timeout'); + } + throw error; + } + } +} + // Configuration schema for Smithery interface ServerConfig { apiUrl?: string; + baoziApiUrl?: string; requestTimeout?: number; } @@ -114,11 +176,15 @@ function createServer(config?: ServerConfig) { config?.apiUrl || BASE_URL, config?.requestTimeout || DEFAULT_TIMEOUT ); + const baoziClient = new BaoziAPIClient( + config?.baoziApiUrl || BAOZI_BASE_URL, + config?.requestTimeout || DEFAULT_TIMEOUT + ); const server = new Server( { name: 'dflow-mcp-server', - version: '1.0.0', + version: '1.1.0', }, { capabilities: { @@ -907,6 +973,300 @@ const TOOLS: Tool[] = [ destructiveHint: false, }, }, + + // ═══════════════════════════════════════════════════════════════════════════ + // Baozi.bet — Decentralized Prediction Markets on Solana + // https://baozi.bet | Program: FWyTPzm5cfJwRKzfkscxozatSxF6Qu78JQovQUwKPruJ + // Pari-mutuel pools • SOL-native • AI agent-friendly • 69 MCP tools + // ═══════════════════════════════════════════════════════════════════════════ + + { + name: 'baozi_get_markets', + title: 'Baozi: List Markets', + description: 'Get active prediction markets from Baozi.bet on Solana. Returns binary (Yes/No) and race (multi-outcome) pari-mutuel markets with live pool sizes, odds, and closing times. Markets are settled in SOL with on-chain oracle resolution.', + inputSchema: { + type: 'object', + properties: { + status: { + type: 'string', + enum: ['Active', 'Closed', 'Resolved', 'Cancelled', 'Paused'], + description: 'Filter by market status (default: Active)', + }, + limit: { + type: 'integer', + minimum: 1, + maximum: 100, + description: 'Number of markets to return (default: 50, max: 100)', + }, + offset: { + type: 'integer', + minimum: 0, + description: 'Pagination offset', + }, + }, + required: [], + }, + annotations: { + title: 'Baozi: List Markets', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_market', + title: 'Baozi: Get Market Details', + description: 'Get detailed information about a specific Baozi.bet prediction market by its Solana public key. Returns question, pool sizes, odds percentages, status, closing time, fees, and outcome labels.', + inputSchema: { + type: 'object', + properties: { + publicKey: { + type: 'string', + description: 'Solana public key (base58) of the market account', + }, + }, + required: ['publicKey'], + }, + annotations: { + title: 'Baozi: Get Market Details', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_agent_markets', + title: 'Baozi: Agent-Optimized Market List', + description: 'Get markets optimized for AI agent consumption from Baozi.bet. Supports filtering by betting status to only show markets currently accepting bets. Returns simplified market data ideal for automated trading strategies.', + inputSchema: { + type: 'object', + properties: { + status: { + type: 'string', + enum: ['Active', 'Closed', 'Resolved', 'Cancelled', 'Paused'], + description: 'Filter by market status (default: Active)', + }, + betting_open: { + type: 'boolean', + description: 'Only return markets currently accepting bets (default: false)', + }, + limit: { + type: 'integer', + minimum: 1, + maximum: 100, + description: 'Number of markets to return (default: 50)', + }, + }, + required: [], + }, + annotations: { + title: 'Baozi: Agent-Optimized Market List', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_quote', + title: 'Baozi: Get Bet Quote', + description: 'Calculate the expected payout for a potential bet on a Baozi.bet market BEFORE placing it. Returns expected payout in SOL, potential profit, implied odds, decimal odds, fee breakdown, and updated pool projections. Essential for evaluating bet profitability.', + inputSchema: { + type: 'object', + properties: { + market: { + type: 'string', + description: 'Solana public key of the market', + }, + side: { + type: 'string', + enum: ['Yes', 'No'], + description: 'Which outcome to bet on', + }, + amount: { + type: 'number', + minimum: 0.01, + maximum: 100, + description: 'Bet amount in SOL (min: 0.01, max: 100)', + }, + }, + required: ['market', 'side', 'amount'], + }, + annotations: { + title: 'Baozi: Get Bet Quote', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_positions', + title: 'Baozi: Get Wallet Positions', + description: 'Get all prediction market positions (bets) for a Solana wallet address on Baozi.bet. Returns both binary and race market positions with current market data, potential payouts, and whether each position is winning.', + inputSchema: { + type: 'object', + properties: { + wallet: { + type: 'string', + description: 'Solana wallet address (base58 public key)', + }, + }, + required: ['wallet'], + }, + annotations: { + title: 'Baozi: Get Wallet Positions', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_market_metadata', + title: 'Baozi: Get Market Metadata', + description: 'Fetch off-chain metadata (description, rules, images, categories, tags, event times) for one or more Baozi.bet markets. Accepts comma-separated market IDs for batch lookups.', + inputSchema: { + type: 'object', + properties: { + marketIds: { + type: 'string', + description: 'Comma-separated Solana public keys of markets', + }, + }, + required: ['marketIds'], + }, + annotations: { + title: 'Baozi: Get Market Metadata', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_agent_info', + title: 'Baozi: Agent Kitchen Info', + description: 'Get comprehensive information about the Baozi.bet agent ecosystem including registered agent count, recent activity, MCP server details, fee structure, market types, and step-by-step registration guide. This is the starting point for any AI agent wanting to participate in Baozi prediction markets.', + inputSchema: { + type: 'object', + properties: {}, + required: [], + }, + annotations: { + title: 'Baozi: Agent Kitchen Info', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_oracle_proofs', + title: 'Baozi: Oracle Resolution Proofs', + description: 'Retrieve oracle resolution proofs from the Baozi.bet "Grandma Mei" oracle system. Each proof includes the data source, evidence, and resolution rationale used to settle a prediction market. Supports filtering by market layer (official, labs, private).', + inputSchema: { + type: 'object', + properties: { + layer: { + type: 'string', + enum: ['official', 'labs', 'private', 'all'], + description: 'Filter proofs by market layer (default: all)', + }, + }, + required: [], + }, + annotations: { + title: 'Baozi: Oracle Resolution Proofs', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_skill_docs', + title: 'Baozi: Protocol Documentation', + description: 'Get the complete Baozi.bet protocol documentation (SKILL.md) — the definitive reference for building on Baozi. Covers all 69 MCP tools, PDA seeds, account discriminators, fee structures, market types, oracle system, affiliate program, and integration guides.', + inputSchema: { + type: 'object', + properties: {}, + required: [], + }, + annotations: { + title: 'Baozi: Protocol Documentation', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_guardrails', + title: 'Baozi: Market Creation Rules', + description: 'Get the pari-mutuel guardrails (rules v7.2) that govern which prediction markets are allowed on Baozi.bet. Includes allowed market types (Type A: scheduled events, Type B: measurement periods), banned categories, timing requirements, and validation checklists. MUST READ before creating any market.', + inputSchema: { + type: 'object', + properties: {}, + required: [], + }, + annotations: { + title: 'Baozi: Market Creation Rules', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_program_idl', + title: 'Baozi: Program IDL', + description: 'Get the Anchor IDL (Interface Definition Language) for the Baozi prediction markets Solana program. Contains all instruction definitions, account schemas, PDA seeds, and type definitions needed for direct on-chain interaction via RPC.', + inputSchema: { + type: 'object', + properties: {}, + required: [], + }, + annotations: { + title: 'Baozi: Program IDL', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, + { + name: 'baozi_get_share_card', + title: 'Baozi: Generate Share Card', + description: 'Generate a 1200x630 PNG share card image for a Baozi.bet prediction market. Shows market question, live YES/NO odds bar, pool size, and optional user position and affiliate branding. Perfect for social media sharing (Twitter/OG standard).', + inputSchema: { + type: 'object', + properties: { + market: { + type: 'string', + description: 'Solana public key of the market', + }, + wallet: { + type: 'string', + description: 'Optional wallet address to show user\'s position on the card', + }, + ref: { + type: 'string', + description: 'Optional affiliate referral code to display on the card', + }, + }, + required: ['market'], + }, + annotations: { + title: 'Baozi: Generate Share Card', + readOnlyHint: true, + idempotentHint: true, + openWorldHint: true, + destructiveHint: false, + }, + }, ]; // Handle list tools request @@ -945,6 +1305,28 @@ server.setRequestHandler(ListPromptsRequestSchema, async () => { }, ], }, + { + name: 'baozi_market_analysis', + description: 'Analyze Baozi.bet Solana prediction markets — find the best opportunities by comparing odds, pool sizes, and closing times across active markets', + arguments: [ + { + name: 'focus', + description: 'Focus area: "highest-volume", "best-odds", "closing-soon", or "new-markets" (default: highest-volume)', + required: false, + }, + ], + }, + { + name: 'cross_platform_comparison', + description: 'Compare prediction markets across DFlow/Kalshi (centralized, CFTC-regulated) and Baozi.bet (decentralized, Solana). Find the same events on both platforms and compare odds, fees, and liquidity.', + arguments: [ + { + name: 'topic', + description: 'Topic to search across both platforms (e.g., "elections", "crypto", "sports")', + required: true, + }, + ], + }, ], }; }); @@ -984,6 +1366,36 @@ server.setRequestHandler(GetPromptRequestSchema, async (request) => { }; } + if (name === 'baozi_market_analysis') { + const focus = args?.focus || 'highest-volume'; + return { + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Analyze Baozi.bet Solana prediction markets with focus on "${focus}". Use baozi_get_markets to fetch active markets, then for the most interesting ones use baozi_get_quote to evaluate potential bets. Provide a summary of the best opportunities including odds, pool sizes, and closing times. Baozi uses pari-mutuel pools where odds shift with each bet — analyze current pool distributions.`, + }, + }, + ], + }; + } + + if (name === 'cross_platform_comparison') { + const topic = args?.topic || 'current events'; + return { + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Compare prediction markets about "${topic}" across DFlow/Kalshi and Baozi.bet. Use search_events for DFlow and baozi_get_markets for Baozi. Compare: (1) Available markets on the same topics, (2) Odds/pricing differences, (3) Fee structures (Kalshi uses order book vs Baozi 2.5-3% pari-mutuel), (4) Liquidity/volume, (5) Settlement mechanism (centralized vs on-chain oracle). Highlight any arbitrage opportunities between CeFi and DeFi markets.`, + }, + }, + ], + }; + } + throw new McpError(ErrorCode.InvalidRequest, `Unknown prompt: ${name}`); }); @@ -1009,6 +1421,24 @@ server.setRequestHandler(ListResourcesRequestSchema, async () => { description: 'Complete API documentation and usage examples', mimeType: 'text/markdown', }, + { + uri: 'baozi://markets', + name: 'Baozi Active Markets', + description: 'Currently active Solana prediction markets on Baozi.bet with live pari-mutuel odds', + mimeType: 'application/json', + }, + { + uri: 'baozi://agents', + name: 'Baozi Agent Ecosystem', + description: 'Agent Kitchen info — registered agents, MCP tools, fees, and registration guide', + mimeType: 'application/json', + }, + { + uri: 'baozi://docs', + name: 'Baozi Protocol Documentation', + description: 'Complete Baozi.bet protocol documentation covering all 69 MCP tools, PDA seeds, and integration guides', + mimeType: 'text/markdown', + }, ], }; }); @@ -1070,6 +1500,45 @@ For full documentation, visit: https://dflow.opensvm.com }; } + if (uri === 'baozi://markets') { + const markets = await baoziClient.get('/api/v4/markets', { status: 'Active', limit: 20 }); + return { + contents: [ + { + uri, + mimeType: 'application/json', + text: JSON.stringify(markets, null, 2), + }, + ], + }; + } + + if (uri === 'baozi://agents') { + const agents = await baoziClient.get('/api/v4/agents'); + return { + contents: [ + { + uri, + mimeType: 'application/json', + text: JSON.stringify(agents, null, 2), + }, + ], + }; + } + + if (uri === 'baozi://docs') { + const docs = await baoziClient.get('/api/skill'); + return { + contents: [ + { + uri, + mimeType: 'text/markdown', + text: typeof docs === 'string' ? docs : docs.content || JSON.stringify(docs), + }, + ], + }; + } + throw new McpError(ErrorCode.InvalidRequest, `Unknown resource: ${uri}`); }); @@ -1194,6 +1663,82 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { result = await apiClient.get('/api/v1/search', toolArgs); break; + // ═══ Baozi.bet Solana Prediction Markets ═══ + + case 'baozi_get_markets': + result = await baoziClient.get('/api/v4/markets', { + status: toolArgs.status || 'Active', + limit: toolArgs.limit || 50, + offset: toolArgs.offset || 0, + }); + break; + + case 'baozi_get_market': + result = await baoziClient.get(`/api/v4/market/${toolArgs.publicKey}`); + break; + + case 'baozi_get_agent_markets': + result = await baoziClient.get('/api/v4/agent/markets', { + status: toolArgs.status || 'Active', + betting_open: toolArgs.betting_open, + limit: toolArgs.limit || 50, + }); + break; + + case 'baozi_get_quote': + result = await baoziClient.get('/api/v4/quote', { + market: toolArgs.market, + side: toolArgs.side, + amount: toolArgs.amount, + }); + break; + + case 'baozi_get_positions': + result = await baoziClient.get(`/api/v4/positions/${toolArgs.wallet}`); + break; + + case 'baozi_get_market_metadata': + result = await baoziClient.get('/api/markets/metadata', { + marketIds: toolArgs.marketIds, + }); + break; + + case 'baozi_get_agent_info': + result = await baoziClient.get('/api/v4/agents'); + break; + + case 'baozi_get_oracle_proofs': + result = await baoziClient.get('/api/agents/proofs', { + layer: toolArgs.layer || 'all', + }); + break; + + case 'baozi_get_skill_docs': + result = await baoziClient.get('/api/skill'); + break; + + case 'baozi_get_guardrails': + result = await baoziClient.get('/api/pari-mutuel-guardrails'); + break; + + case 'baozi_get_program_idl': + result = await baoziClient.get('/api/mcp/idl'); + break; + + case 'baozi_get_share_card': { + const cardParams: Record = { market: toolArgs.market }; + if (toolArgs.wallet) cardParams.wallet = toolArgs.wallet; + if (toolArgs.ref) cardParams.ref = toolArgs.ref; + const cardUrl = new URL(`${baoziClient.baseUrl}/api/share/card`); + Object.entries(cardParams).forEach(([k, v]) => cardUrl.searchParams.set(k, v)); + result = { + imageUrl: cardUrl.toString(), + format: 'PNG 1200x630', + description: 'Share card image URL — open in browser or embed in social media posts', + }; + break; + } + default: throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`); } @@ -1225,7 +1770,11 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { // Export for Smithery (stateless server factory) export default function({ config }: { config?: ServerConfig }) { - return createServer(config); + return createServer(config ? { + apiUrl: config.apiUrl, + baoziApiUrl: config.baoziApiUrl, + requestTimeout: config.requestTimeout, + } : undefined); } // Also run as STDIO server when executed directly