### Build and Run Commands Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/configuration.md Installs dependencies, builds the project, and starts the application. ```bash npm install npm run build npm start ``` -------------------------------- ### Create .env File Example Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/configuration.md Copies the example .env file to create a new one for local configuration. ```bash cp .env.example .env ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Run this command in your project directory to install necessary npm packages. ```bash npm install ``` -------------------------------- ### Start the Server Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Run this command to start the EVE Online Market MCP Server. The server will indicate it is running on stdio. ```bash npm start ``` -------------------------------- ### Page Parameter Example Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/tools-reference.md Optional parameter for paginating market order results. Queries start at page 1 and typically return around 40 orders per page. ```typescript page: z.number().optional().describe("Which page to query, starts at 1") ``` -------------------------------- ### Build and Run MCP Server Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Follow these commands to edit the main server file, rebuild the project, and start the server. ```bash # Edit the file nano src/index.ts # Rebuild npm run build # Start server npm start ``` -------------------------------- ### Example: Get Tritanium Orders in a Structure Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/structure-tools.md Demonstrates how to call the 'get-structure-type-orders' tool to retrieve market orders for Tritanium, specifying the page number. Also shows how to get the first page of orders when the page parameter is omitted. ```typescript // Get page 1 of Tritanium orders in a structure const response = await callTool("get-structure-type-orders", { structure_id: 1234567890, type_id: 34, page: 1 }); // Get first page of orders const orders = await callTool("get-structure-type-orders", { structure_id: 1234567890, type_id: 34 }); ``` -------------------------------- ### Set up .env file for EVE Online SSO Source: https://github.com/kongyo2/eve-online-mcp/blob/main/README.md Copy the example .env file and edit it to include your ESI client ID and secret. This is a prerequisite for authentication. ```bash cp .env.example .env # .envファイルを編集して認証情報を設定 ``` -------------------------------- ### Call Get Market History Tool Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/market-tools.md Example of how to call the 'get-market-history' tool to retrieve historical market data. Ensure you have the correct region_id and type_id for the desired item and location. ```typescript // Get 30+ days of historical data for Tritanium in The Forge const response = await callTool("get-market-history", { region_id: 10000002, type_id: 34 }); ``` -------------------------------- ### Order Type Parameter Example Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/tools-reference.md Defines the type of market orders to retrieve, with options for 'buy', 'sell', or 'all'. Defaults to 'all' if not specified. ```typescript order_type: z.enum(["buy", "sell", "all"]).default("all") ``` -------------------------------- ### Authenticate Tool Usage Example Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/authentication-tools.md Demonstrates how to use the 'authenticate' tool after the user authorizes on the EVE SSO callback URL. It shows how to parse the response and check for the access token. ```typescript // After user authorizes on EVE SSO callback URL const response = await callTool("authenticate", { code: "authorization-code-from-callback" }); const tokenData = JSON.parse(response.content[0].text); if (tokenData.access_token) { // Save tokens for later use console.log(`Authenticated as ${tokenData.character_name}`); } ``` -------------------------------- ### Example Callback Handler Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/configuration.md Illustrates a basic Express.js route handler for processing the callback from EVE SSO. It extracts the 'code' and 'state' parameters for subsequent authentication. ```typescript // In your application app.get("/callback", (req, res) => { const { code, state } = req.query; // Validate state matches what was sent in get-auth-url // Call authenticate tool with code }); ``` -------------------------------- ### Get All Market Prices Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Fetch all market prices using the 'get-market-prices' tool. Parses the response content to display the first price entry. ```typescript const response = await callTool("get-market-prices"); const prices = JSON.parse(response.content[0].text); console.log(prices[0]); // Output: { type_id: 34, adjusted_price: 123.45, average_price: 125.67 } ``` -------------------------------- ### Type ID Parameter Example Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/tools-reference.md Examples of item type IDs used to filter market orders or historical data. These IDs uniquely identify specific in-game items. ```typescript type_id: z.number().describe("Item type ID to filter orders") ``` -------------------------------- ### Call get-market-stats Tool Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/market-tools.md Example of how to call the 'get-market-stats' tool with a specific region ID. This demonstrates the expected input format and the structure of the returned market statistics. ```typescript // Get market statistics for The Forge const response = await callTool("get-market-stats", { region_id: 10000002 }); // Returns: [ { name: "...", value: ... }, ... ] ``` -------------------------------- ### Region ID Parameter Example Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/tools-reference.md Examples of region IDs used for market-related tools. These IDs specify the geographical area for market data retrieval. ```typescript region_id: z.number().describe("Region ID to get market orders from") ``` -------------------------------- ### Structure ID Parameter Example Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/tools-reference.md Parameter for specifying a structure ID to retrieve market orders from a player-owned station. ```typescript structure_id: z.number().describe("Structure ID to get market orders from") ``` -------------------------------- ### Get Market Prices for All Items Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/market-tools.md Retrieves current market prices for all tradeable items in EVE Online. This tool accepts no input parameters. ```typescript server.tool( "get-market-prices", "Get market prices for all items in EVE Online", {}, async () => Promise ); ``` ```typescript const response = await callTool("get-market-prices"); // Response contains JSON array of all market prices ``` -------------------------------- ### Add New Tool to MCP Server Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Register a new tool with the MCP server by defining its input schema using Zod and providing an implementation handler. This example shows how to define a string parameter and its handler. ```typescript server.tool( "my-new-tool", "Description of what it does", { parameter: z.string().describe("Parameter description") }, async ({ parameter }) => { // Implementation return { content: [{ type: "text", text: JSON.stringify(result) }] }; } ); ``` -------------------------------- ### Authenticate and Access Private Structures Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Guides through the OAuth2 authentication flow to obtain an access token and subsequently use it to fetch private structure orders. ```typescript // Step 1: Get authentication URL const authResponse = await callTool("get-auth-url", { state: "unique-random-string" }); const authUrl = authResponse.content[0].text; console.log("Redirect user to:", authUrl); // Step 2: After user authorizes, get code from callback // (This happens in your callback handler) // Step 3: Exchange code for tokens const tokenResponse = await callTool("authenticate", { code: "code-from-callback" }); const tokenData = JSON.parse(tokenResponse.content[0].text); console.log(`Authenticated as ${tokenData.character_name}`); // Step 4: Use token to access private structures const orders = await callTool("get-structure-orders", { structure_id: 1234567890, token: tokenData.access_token }); ``` -------------------------------- ### Define get-market-stats Tool Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/market-tools.md Defines the 'get-market-stats' tool with its signature, input parameters, and asynchronous function handler. This setup is used to register the tool within the system. ```typescript server.tool( "get-market-stats", "Get market statistics for a region", { region_id: z.number() }, async ({ region_id }) => Promise ); ``` -------------------------------- ### Define Get Market History Tool Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/market-tools.md Defines the 'get-market-history' tool with its parameters and asynchronous handler. This is used to set up the tool's functionality within the server. ```typescript server.tool( "get-market-history", "Get market history for a specific item in a region", { region_id: z.number(), type_id: z.number() }, async ({ region_id, type_id }) => Promise ); ``` -------------------------------- ### Get Structure Type Orders Tool Signature Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/structure-tools.md Defines the signature for the 'get-structure-type-orders' tool, specifying input parameters and the expected asynchronous return type. ```typescript server.tool( "get-structure-type-orders", "Get all market orders for a specific type in a structure", { structure_id: z.number(), type_id: z.number(), page: z.number().optional() }, async ({ structure_id, type_id, page }) => Promise ); ``` -------------------------------- ### verifyToken Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/helper-functions.md Verifies an access token with the EVE SSO and retrieves associated character information. This function makes a GET request to the EVE SSO verification endpoint. ```APIDOC ## verifyToken ### Description Verifies an access token with the EVE SSO and returns character information. This is used to confirm the validity of an access token and identify the associated character. ### Method GET ### Endpoint https://login.eveonline.com/oauth/verify ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript GET https://login.eveonline.com/oauth/verify Authorization: Bearer {token} ``` ### Response #### Success Response (200) - **CharacterID** (number) - The unique ID of the character. - **CharacterName** (string) - The name of the character. - **ExpiresOn** (string) - The expiration date and time of the token. - **Scopes** (string) - The scopes granted by the token. - **TokenType** (string) - The type of token (e.g., 'Bearer'). - **CharacterOwnerHash** (string) - A hash representing the owner of the character. #### Response Example ```json { "CharacterID": 123456789, "CharacterName": "Example Character", "ExpiresOn": "2024-03-15T10:00:00Z", "Scopes": "esi_planets_read esi_universe_read", "TokenType": "Bearer", "CharacterOwnerHash": "a_unique_hash_string" } ``` ### Throws - `Error: "Failed to verify token"` - If the verification endpoint returns a non-OK response. ``` -------------------------------- ### Get Market Group Statistics Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/market-tools.md Use this tool to retrieve aggregated buy and sell order statistics for a specific item type within an EVE Online region. Ensure you have the correct region and item type IDs. ```typescript server.tool( "get-market-groups", "Get grouped market data for a region and type", { region_id: z.number(), type_id: z.number() }, async ({ region_id, type_id }) => Promise ); ``` ```typescript // Get buy/sell statistics for Tritanium in The Forge const response = await callTool("get-market-groups", { region_id: 10000002, type_id: 34 }); // Returns: { buy: {...}, sell: {...} } ``` -------------------------------- ### Verify Eve Online Access Token Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/helper-functions.md This function verifies an access token with the EVE SSO, returning detailed character information. It performs a GET request to the SSO verify endpoint, including the token in the Authorization header. ```typescript async function verifyToken(token: string): Promise // Called internally during authenticate const character = await verifyToken(accessToken); // { CharacterID: 123456, CharacterName: "Player Name", ... } ``` ```http GET https://login.eveonline.com/oauth/verify Authorization: Bearer {token} ``` -------------------------------- ### Build the Project Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Execute this command to compile and build the project. ```bash npm run build ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Create a .env file with your EVE Online API credentials and callback URL. Obtain credentials from https://developers.eveonline.com/. ```dotenv EVE_CLIENT_ID=your-client-id-here EVE_CLIENT_SECRET=your-client-secret-here EVE_CALLBACK_URL=http://localhost:3000/callback ``` -------------------------------- ### Development .env Configuration Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/configuration.md Specifies client credentials and callback URL for local development using HTTP. ```dotenv EVE_CLIENT_ID=dev-client-id EVE_CLIENT_SECRET=dev-client-secret EVE_CALLBACK_URL=http://localhost:3000/callback ``` -------------------------------- ### Initialize McpServer Instance Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/mcp-server.md Initializes the McpServer with a name, version, and capability declarations. The capabilities object is used to declare resource and tool capabilities, which are empty in this configuration as tools are registered dynamically. ```typescript const server = new McpServer({ name: "eve-online-market", version: "1.0.0", capabilities: { resources: {}, tools: {}, }, }); ``` -------------------------------- ### Get Structure Orders Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/structure-tools.md Retrieves all market orders from a specific structure. Use this to fetch order data for a given structure ID, with optional pagination. ```typescript server.tool( "get-structure-orders", "Get all market orders in a structure", { structure_id: z.number(), page: z.number().optional() }, async ({ structure_id, page }) => Promise ); ``` ```typescript // Get page 1 of orders from a structure const response = await callTool("get-structure-orders", { structure_id: 1234567890, page: 1 }); // Get first page (default) const firstPage = await callTool("get-structure-orders", { structure_id: 1234567890 }); ``` -------------------------------- ### Manual .env File Configuration Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/configuration.md Manually defines the EVE Online API client ID, client secret, and callback URL in the .env file. ```dotenv EVE_CLIENT_ID=your-client-id EVE_CLIENT_SECRET=your-client-secret EVE_CALLBACK_URL=http://localhost:3000/callback ``` -------------------------------- ### Production .env Configuration Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/configuration.md Specifies client credentials and callback URL for production deployment, requiring HTTPS. ```dotenv EVE_CLIENT_ID=prod-client-id EVE_CLIENT_SECRET=prod-client-secret EVE_CALLBACK_URL=https://yourdomain.com/callback ``` -------------------------------- ### Mock MCP Client for Unit Tests Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/integration-guide.md Implement a mock client to simulate MCP responses for unit testing. Use setFixture to define expected outputs for specific tool calls and parameters. ```typescript class MockMCPClient { private fixtures: Map = new Map(); setFixture(toolName: string, params: string, data: any) { this.fixtures.set(`${toolName}:${params}`, data); } async callTool(toolName: string, params: Record) { const key = `${toolName}:${JSON.stringify(params)}`; const data = this.fixtures.get(key); if (!data) { throw new Error(`No fixture for ${key}`); } return { content: [{ type: "text", text: JSON.stringify(data) }] }; } } // Test usage const mockClient = new MockMCPClient(); mockClient.setFixture("get-market-prices", "{}", [ { type_id: 34, adjusted_price: 100, average_price: 105 } ]); const prices = await mockClient.callTool("get-market-prices", {}); // Returns mocked data for testing ``` -------------------------------- ### Registering an MCP Tool Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/README.md Register a new tool with the MCP server, providing its name, description, input schema, and handler function. This pattern is fundamental for extending the server's functionality. ```typescript server.tool(toolName, description, inputSchema, handler); ``` -------------------------------- ### Get Historical Market Data Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Fetch historical market data for a specific item type in a region. Iterates through the history and logs daily price ranges and averages. ```typescript const response = await callTool("get-market-history", { region_id: 10000002, type_id: 34 }); const history = JSON.parse(response.content[0].text); history.forEach(day => { console.log(`${day.date}: ${day.lowest} - ${day.highest} (avg: ${day.average})`); }); ``` -------------------------------- ### Monitor All Structure Orders with Pagination Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/integration-guide.md Fetches all market orders for a given structure, handling pagination automatically. Useful for comprehensive market analysis. ```typescript async function getAllStructureOrders( structureId: number, accessToken?: string ): Promise { const allOrders: MarketOrder[] = []; let page = 1; while (true) { const result = await client.callTool("get-structure-orders", { structure_id: structureId, page, token: accessToken // If available }); const orders = JSON.parse(result.content[0].text); if (orders.length === 0) break; allOrders.push(...orders); page++; } return allOrders; } // Usage async function monitorStructureMarket(structureId: number) { const orders = await getAllStructureOrders(structureId); // Group by item type const byType = new Map(); orders.forEach(order => { const list = byType.get(order.type_id) ?? []; list.push(order); byType.set(order.type_id, list); }); // Analyze byType.forEach((orders, typeId) => { const buyOrders = orders.filter(o => o.is_buy_order); const sellOrders = orders.filter(o => !o.is_buy_order); const buyTotal = buyOrders.reduce((sum, o) => sum + o.volume_remain, 0); const sellTotal = sellOrders.reduce((sum, o) => sum + o.volume_remain, 0); console.log(`Type ${typeId}: ${buyTotal} buy | ${sellTotal} sell`); }); } ``` -------------------------------- ### Get EVE Online Authentication URL Source: https://github.com/kongyo2/eve-online-mcp/blob/main/README.md Call the 'get-auth-url' tool to obtain the URL for user redirection during the authentication process. Ensure a unique state string is provided for security. ```typescript const authUrlResponse = await callTool("get-auth-url", { state: "unique-state-string" }); // ユーザーをauthUrlResponseのURLにリダイレクト ``` -------------------------------- ### Get Market Orders by Region Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/market-tools.md Retrieves market orders from a specific region with optional filtering by item type and order type. Requires region_id and optionally accepts type_id and order_type. ```typescript server.tool( "get-market-orders", "Get market orders from a specific region", { region_id: z.number(), type_id: z.number().optional(), order_type: z.enum(["buy", "sell", "all"]).default("all") }, async ({ region_id, type_id, order_type }) => Promise ); ``` ```typescript // Get all buy orders for Tritanium (type_id: 34) in The Forge (region_id: 10000002) const response = await callTool("get-market-orders", { region_id: 10000002, type_id: 34, order_type: "buy" }); // Get all orders in a region const allOrders = await callTool("get-market-orders", { region_id: 10000002, order_type: "all" }); ``` -------------------------------- ### Get Item Orders in a Region Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Retrieve market orders for a specific item type within a given region and order type (sell or buy). Logs the number of found orders. ```typescript const response = await callTool("get-market-orders", { region_id: 10000002, // The Forge type_id: 34, // Tritanium order_type: "sell" }); const orders = JSON.parse(response.content[0].text); console.log(`Found ${orders.length} sell orders`); ``` -------------------------------- ### Tool Registration Signature Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/mcp-server.md Defines the signature for registering tools with the McpServer. Each tool requires a unique name, a description, a Zod schema for input validation, and an asynchronous handler function to execute the tool's logic. ```typescript server.tool( toolName: string, description: string, inputSchema: object, // Zod schema for parameters handler: async (args) => ToolResponse ); ``` -------------------------------- ### Paginate Structure Orders Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Iteratively fetch all orders for a given structure by handling pagination. The loop continues as long as new orders are returned. ```typescript let allOrders = []; let page = 1; let hasMore = true; while (hasMore) { const response = await callTool("get-structure-orders", { structure_id: 1234567890, page: page }); const orders = JSON.parse(response.content[0].text); if (orders.length === 0) { hasMore = false; } else { allOrders.push(...orders); page++; } } console.log(`Total orders: ${allOrders.length}`); ``` -------------------------------- ### Access Structure Market Data with Token Source: https://github.com/kongyo2/eve-online-mcp/blob/main/README.md To access market data for a specific structure, call the 'get-structure-orders' tool. Provide the structure ID, page number, and a valid ESI access token with the necessary scopes. ```typescript const structureOrders = await callTool("get-structure-orders", { structure_id: 1234567890, page: 1, token: "your-access-token" }); ``` -------------------------------- ### get-market-prices Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/market-tools.md Retrieves current market prices for all tradeable items in EVE Online. This tool accepts no input parameters. ```APIDOC ## get-market-prices ### Description Retrieves current market prices for all tradeable items in EVE Online. ### Method POST (via tool invocation) ### Endpoint N/A (Tool Function) ### Parameters None. ### Return Type ```json { "content": [ { "type": "text", "text": "JSON.stringify(Array<{ type_id: number, adjusted_price: number, average_price: number }>, null, 2)" } ] } ``` ### Response Fields - **type_id** (number) - Unique identifier for the item type in EVE Online - **adjusted_price** (number) - Adjusted price used in calculations (0 if unavailable) - **average_price** (number) - Average market price across all regions (0 if unavailable) ### Example ```typescript const response = await callTool("get-market-prices"); // Response contains JSON array of all market prices ``` ### Throws - `Error: Rate limit exceeded` - When ESI rate limit has been exceeded - `Error: HTTP error! status: {status}` - HTTP request failed - `Error: ESI Error: {error}` - ESI API returned an error with details ``` -------------------------------- ### TypeScript Trading Opportunity Finder Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/integration-guide.md Identifies potential arbitrage opportunities by comparing buy and sell prices across regions. Requires 'get-market-prices' and 'get-market-groups' tools. Analyzes a sample subset of items. ```typescript interface TradingOpportunity { typeId: number; buyPrice: number; sellPrice: number; margin: number; marginPct: number; } async function findArbitrageOpportunities( regionId: number, minMarginPct: number = 5 ): Promise { const opportunities: TradingOpportunity[] = []; // Get all prices first const priceResult = await client.callTool("get-market-prices", {}); const allPrices = JSON.parse(priceResult.content[0].text); // For each item, get the regional spread for (const price of allPrices.slice(0, 100)) { // Sample subset const groupResult = await client.callTool("get-market-groups", { region_id: regionId, type_id: price.type_id }); const group = JSON.parse(groupResult.content[0].text); const buyPrice = group.buy.weighted_average; const sellPrice = group.sell.weighted_average; if (buyPrice > 0 && sellPrice > 0) { const margin = sellPrice - buyPrice; const marginPct = (margin / buyPrice) * 100; if (marginPct >= minMarginPct) { opportunities.push({ typeId: price.type_id, buyPrice, sellPrice, margin, marginPct }); } } } return opportunities.sort((a, b) => b.marginPct - a.marginPct); } ``` -------------------------------- ### Handle Failed Token Verification Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/errors.md This snippet demonstrates how to handle token verification failures, which can occur during the authentication tool's execution. It logs a message if authentication fails. ```typescript // This occurs during authenticate tool execution const response = await callTool("authenticate", { code: authCode }); if (response.content[0].text.includes("Authentication failed")) { console.log("Token verification failed"); } ``` -------------------------------- ### Authenticate Tool Signature Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/authentication-tools.md Defines the signature for the 'authenticate' tool, specifying its name, a brief description, input parameters, and the asynchronous function to execute. ```typescript server.tool( "authenticate", "Exchange authorization code for access token", { code: z.string() }, async ({ code }) => Promise ); ``` -------------------------------- ### TypeScript Price Tracking System Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/integration-guide.md Tracks historical price data for a given item type. Useful for monitoring price fluctuations over time. Requires a client with a 'get-market-prices' tool. ```typescript interface PriceSnapshot { timestamp: number; prices: Map; } class PriceTracker { private history: PriceSnapshot[] = []; async captureSnapshot() { const result = await client.callTool("get-market-prices", {}); const prices = JSON.parse(result.content[0].text); const map = new Map(); prices.forEach(p => { map.set(p.type_id, { adjusted: p.adjusted_price, average: p.average_price }); }); this.history.push({ timestamp: Date.now(), prices: map }); } getPriceChange(typeId: number, minutesAgo: number): number | null { const cutoff = Date.now() - (minutesAgo * 60 * 1000); const old = this.history.find(s => s.timestamp <= cutoff); const new_ = this.history[this.history.length - 1]; if (!old || !new_) return null; const oldPrice = old.prices.get(typeId)?.average ?? 0; const newPrice = new_.prices.get(typeId)?.average ?? 0; return newPrice - oldPrice; } } ``` -------------------------------- ### Analyze Market Buy/Sell Spreads Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Calculates and displays the buy/sell spread percentage for a given item type in a region by fetching market group data. ```typescript const response = await callTool("get-market-groups", { region_id: 10000002, type_id: 34 }); const groups = JSON.parse(response.content[0].text); const buyPrice = groups.buy.weighted_average; const sellPrice = groups.sell.weighted_average; const spread = sellPrice - buyPrice; const spreadPct = (spread / buyPrice) * 100; console.log(`Buy: ${buyPrice.toFixed(2)}`); console.log(`Sell: ${sellPrice.toFixed(2)}`); console.log(`Spread: ${spread.toFixed(2)} (${spreadPct.toFixed(1)}%)`); ``` -------------------------------- ### EVE_CALLBACK_URL Environment Variable Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/configuration.md Specifies the OAuth2 callback URL for EVE Online SSO redirects. It defaults to 'http://localhost:3000/callback' and must match the URL registered in the EVE Developers Portal. ```typescript const EVE_CALLBACK_URL = process.env.EVE_CALLBACK_URL || "http://localhost:3000/callback"; ``` -------------------------------- ### get-auth-url Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/tools-reference.md Generates the EVE Online SSO authentication URL, which is the first step in the OAuth2 flow. Requires a state parameter for CSRF protection. ```APIDOC ## get-auth-url ### Description Generate EVE Online SSO authentication URL. ### Parameters #### Query Parameters - **state** (string) - Required - CSRF protection state value ### Returns Full authentication URL (Plain text URL string) ### Purpose First step of OAuth2 flow. ``` -------------------------------- ### Exchange Authorization Code for Tokens Source: https://github.com/kongyo2/eve-online-mcp/blob/main/README.md After the user authorizes your application, use the 'authenticate' tool with the authorization code received from the callback to exchange it for access and refresh tokens. Save the returned tokens. ```typescript const authResponse = await callTool("authenticate", { code: "authorization-code-from-callback" }); // 返されたトークンを保存 ``` -------------------------------- ### Filter Market Orders by Price Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/quick-start.md Fetch market orders for a specific region and type, then filter them to find orders within a specified maximum price. The cheapest affordable order is then identified. ```typescript const response = await callTool("get-market-orders", { region_id: 10000002, type_id: 34, order_type: "sell" }); const orders = JSON.parse(response.content[0].text); const maxPrice = 500; const affordableOrders = orders.filter(order => order.price <= maxPrice); const cheapest = affordableOrders.sort((a, b) => a.price - b.price)[0]; console.log(`Cheapest at ${cheapest.price} for ${cheapest.volume_total} units`); ``` -------------------------------- ### get-market-stats Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/market-tools.md Retrieves aggregate market statistics for a specified EVE Online region. This tool is useful for analyzing market trends and data. ```APIDOC ## get-market-stats ### Description Retrieves aggregate market statistics for a specified EVE Online region. ### Method POST (Implicitly via tool call) ### Endpoint Not applicable (Tool call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **region_id** (number) - Required - EVE Online region ID ### Request Example ```typescript // Get market statistics for The Forge const response = await callTool("get-market-stats", { region_id: 10000002 }); ``` ### Response #### Success Response (200) - **content** (array) - An array containing market statistics. - Each object in the array has: - **name** (string) - Name of the statistic - **value** (number) - Numeric value of the statistic #### Response Example ```json { "content": [ { "type": "text", "text": "[{\"name\": \"Average Sell Price\", \"value\": 1234.56}, {\"name\": \"Total Volume\", \"value\": 789012}]" } ] } ``` ### Throws - `Error: Rate limit exceeded` - When ESI rate limit has been exceeded - `Error: HTTP error! status: {status}` - HTTP request failed - `Error: ESI Error: {error}` - ESI API returned an error ``` -------------------------------- ### Configure ESI User Agent Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/configuration.md Defines the HTTP User-Agent header for ESI requests. It's recommended to update the GitHub URL to your repository. ```typescript const USER_AGENT = "eve-online-mcp/1.0 (github.com/your-username/eve-online-mcp)"; ``` -------------------------------- ### get-structure-orders Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/structure-tools.md Retrieves all market orders from a specific structure with pagination support. Requires structure ownership or access permissions. ```APIDOC ## get-structure-orders ### Description Retrieves all market orders from a specific structure with pagination support. Requires structure ownership or access permissions. ### Method POST ### Endpoint /get-structure-orders ### Parameters #### Request Body - **structure_id** (number) - Required - Structure ID (station, citadel, etc.) - **page** (number) - Optional - Page number starting at 1 ### Request Example ```json { "structure_id": 1234567890, "page": 1 } ``` ### Response #### Success Response (200) - **content** (array) - Contains an array of structure orders. - **type** (string) - Always "text" - **text** (string) - JSON stringified array of StructureOrder objects. ### StructureOrder Fields - **order_id** (number) - Unique order identifier - **type_id** (number) - Item type ID being traded - **price** (number) - ISK price per unit - **volume_remain** (number) - Units remaining unfilled - **volume_total** (number) - Total units in the order - **is_buy_order** (boolean) - True if buy order, false if sell order - **duration** (number) - Days the order remains active - **issued** (string) - ISO 8601 timestamp when created - **range** (string) - Trade range (e.g., "station", "region") ### Example ```json { "content": [ { "type": "text", "text": "[\n {\n \"order_id\": 12345,\n \"type_id\": 123,\n \"price\": 1000000,\n \"volume_remain\": 100,\n \"volume_total\": 100,\n \"is_buy_order\": false,\n \"duration\": 30,\n \"issued\": \"2023-10-27T10:00:00Z\",\n \"range\": \"station\"\n }\n]" } ] } ``` ### Authentication This endpoint may require authentication depending on structure access permissions. Provide an ESI token if you own or have access to the structure. ### Throws - `Error: Rate limit exceeded` - When ESI rate limit has been exceeded - `Error: HTTP error! status: 403` - Access denied (insufficient permissions) - `Error: HTTP error! status: 404` - Structure not found - `Error: ESI Error: {error}` - ESI API returned an error ``` -------------------------------- ### Connect McpServer with Stdio Transport Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/api-reference/mcp-server.md Connects the initialized McpServer instance to a StdioServerTransport for communication via standard input/output streams. This function also logs a message to the console error stream indicating the server is running. ```typescript async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("EVE Online Market MCP Server running on stdio"); } ``` -------------------------------- ### Batching Requests with BatchProcessor Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/integration-guide.md Use the BatchProcessor class to group multiple requests for the same region and type IDs, reducing the number of API calls. Requests are processed after a 1-second delay. ```typescript interface RequestBatch { typeIds: number[]; regionId: number; handler: (result: T) => void; } class BatchProcessor { private batches: RequestBatch[] = []; private batchInterval: NodeJS.Timeout | null = null; queueRequest( typeIds: number[], regionId: number, handler: (result: T) => void ) { this.batches.push({ typeIds, regionId, handler }); if (!this.batchInterval) { this.batchInterval = setTimeout(() => this.processBatch(), 1000); } } async processBatch() { const grouped = new Map(); for (const batch of this.batches) { const key = batch.regionId; if (!grouped.has(key)) grouped.set(key, []); grouped.get(key)!.push(batch); } for (const [regionId, batches] of grouped) { // Get all unique type IDs const typeIds = new Set(); batches.forEach(b => b.typeIds.forEach(id => typeIds.add(id))); // Fetch once per region for (const typeId of typeIds) { const result = await client.callTool("get-market-groups", { region_id: regionId, type_id: typeId }); // Call all handlers waiting for this type batches.forEach(batch => { if (batch.typeIds.includes(typeId)) { batch.handler(JSON.parse(result.content[0].text)); } }); } } this.batches = []; this.batchInterval = null; } } ``` -------------------------------- ### Session Manager for EVE Online Authentication Source: https://github.com/kongyo2/eve-online-mcp/blob/main/_autodocs/integration-guide.md Manages EVE Online authentication tokens, including initial authentication and automatic refresh. Use this class to store and maintain user session data. ```typescript interface Session { characterId: number; characterName: string; accessToken: string; refreshToken: string; expiresAt: number; tokenType: string; } class SessionManager { private session: Session | null = null; async authenticate(code: string): Promise { const result = await client.callTool("authenticate", { code }); const text = result.content[0].text; if (text.includes("failed")) { throw new Error(text); } const data = JSON.parse(text); this.session = { characterId: data.character_id, characterName: data.character_name, accessToken: data.access_token, refreshToken: data.refresh_token, expiresAt: Date.now() + (data.expires_in * 1000), tokenType: data.token_type }; return this.session; } async refreshIfNeeded(): Promise { if (!this.session) return false; const now = Date.now(); const timeUntilExpiry = this.session.expiresAt - now; // Refresh if less than 5 minutes remaining if (timeUntilExpiry < 5 * 60 * 1000) { const result = await client.callTool("refresh-token", { refresh_token: this.session.refreshToken }); const text = result.content[0].text; if (text.includes("failed")) { this.session = null; return false; } const data = JSON.parse(text); this.session.accessToken = data.access_token; this.session.refreshToken = data.refresh_token; this.session.expiresAt = Date.now() + (data.expires_in * 1000); return true; } return true; } getSession(): Session | null { return this.session; } logout(): void { this.session = null; } } ``` -------------------------------- ### Refresh EVE Online Access Token Source: https://github.com/kongyo2/eve-online-mcp/blob/main/README.md Use the 'refresh-token' tool with a saved refresh token to obtain a new access token when the current one expires. This allows continued access to protected resources. ```typescript const refreshResponse = await callTool("refresh-token", { refresh_token: "saved-refresh-token" }); // 新しいトークンで更新 ```