devopsabcs.AiStockTradeMcpServer 1.0.0-beta.15

This is a prerelease version of devopsabcs.AiStockTradeMcpServer.
dotnet tool install --global devopsabcs.AiStockTradeMcpServer --version 1.0.0-beta.15
                    
This package contains a .NET tool you can call from the shell/command line.
dotnet new tool-manifest
                    
if you are setting up this repo
dotnet tool install --local devopsabcs.AiStockTradeMcpServer --version 1.0.0-beta.15
                    
This package contains a .NET tool you can call from the shell/command line.
#tool dotnet:?package=devopsabcs.AiStockTradeMcpServer&version=1.0.0-beta.15&prerelease
                    
nuke :add-package devopsabcs.AiStockTradeMcpServer --version 1.0.0-beta.15
                    

AiStockTradeApp.McpServer - Model Context Protocol Server

๐Ÿš€ Project Overview

A Model Context Protocol (MCP) server that provides external AI assistants (Claude, ChatGPT, or other MCP-compatible clients) with access to comprehensive stock trading functionality through the AI Stock Trade App API.

๐Ÿ—๏ธ Architecture Role

This project serves as an integration bridge between external AI assistants and the stock trading application:

  • Protocol Implementation - Full MCP specification compliance
  • Tool Registration - Automatic discovery of stock trading tools
  • HTTP Client Integration - Communicates with AiStockTradeApp.Api
  • External AI Access - Enables AI assistants to access stock data
  • Dual Transport Support - STDIO and HTTP communication protocols

Key Responsibilities

  • Stock data access for external AI assistants
  • Real-time market information retrieval
  • Historical data analysis capabilities
  • Stock search and discovery tools
  • System health monitoring for AI clients
  • Utility functions for data generation and analysis

๐Ÿ› ๏ธ Available MCP Tools

Stock Data Tools

  • GetStockQuote - Real-time stock quote data including price, change, and company information
  • GetHistoricalData - Historical price data over a specified number of days (up to 365 days)
  • GetDetailedHistoricalPrices - Detailed historical prices with optional date range filtering
  • SearchStockSymbols - Search for stock symbols by company name or ticker
  • GetStockDetails - Detailed company information including sector, industry, and market cap
  • GetListedStocks - Browse available stocks with pagination support
  • GetRandomListedStock - Get a random stock for investment discovery and exploration
  • GetSystemStatus - Check API system health and availability status

Utility Tools

  • GetRandomNumber - Generate a single random number within a specified range
  • GetRandomNumberList - Generate lists of random numbers with customizable parameters

๐Ÿ”ง Configuration

Environment Variables

The MCP server requires configuration of the Stock Trading API endpoint:

  • STOCK_API_BASE_URL - Base URL for the Stock Trading API
    • Default: http://localhost:5000
    • Production: https://your-api-domain.com

MCP Client Configuration

For Claude Desktop
{
  "inputs": [
    {
      "type": "promptString",
      "id": "stock_api_base_url",
      "description": "Base URL for the Stock Trading API (e.g., http://localhost:5000)",
      "password": false
    }
  ],
  "servers": {
    "AiStockTradeApp.McpServer": {
      "type": "stdio",
      "command": "dotnet",
      "args": [
        "run",
        "--project",
        "C:\\path\\to\\AiStockTradeApp.McpServer\\AiStockTradeApp.McpServer.csproj"
      ],
      "env": {
        "STOCK_API_BASE_URL": "${input:stock_api_base_url}"
      }
    }
  }
}
For Other MCP Clients
{
  "servers": {
    "stock-trading": {
      "type": "stdio",
      "command": "dotnet",
      "args": ["run", "--project", "/path/to/AiStockTradeApp.McpServer"],
      "env": {
        "STOCK_API_BASE_URL": "http://localhost:5000"
      }
    }
  }
}

๐Ÿš€ Development Setup

Prerequisites

  • .NET 9 SDK - Latest version
  • AiStockTradeApp.Api - Must be running on configured port
  • MCP-compatible client - Claude Desktop, compatible AI assistant, or testing tool

Local Development

  1. Start the API backend

    # Start the main API (required dependency)
    dotnet run --project AiStockTradeApp.Api
    
  2. Configure environment

    # Set API base URL (PowerShell)
    $env:STOCK_API_BASE_URL = "http://localhost:5000"
    
    # Set API base URL (Bash)
    export STOCK_API_BASE_URL="http://localhost:5000"
    
  3. Run the MCP server

    # STDIO mode (default for MCP clients)
    dotnet run --project AiStockTradeApp.McpServer
    
    # HTTP mode (for testing)
    dotnet run --project AiStockTradeApp.McpServer --urls "http://localhost:8080"
    

Testing the Server

# Test API connectivity
curl $STOCK_API_BASE_URL/health

# Test MCP server (HTTP mode)
curl http://localhost:8080/health

# View available tools (HTTP mode)
curl http://localhost:8080/tools

๏ฟฝ Project Structure

AiStockTradeApp.McpServer/ โ”œโ”€โ”€ Tools/ โ”‚ โ”œโ”€โ”€ StockTradingTools.cs # MCP tool implementations โ”‚ โ””โ”€โ”€ UtilityTools.cs # Utility tool implementations โ”œโ”€โ”€ Models/ โ”‚ โ”œโ”€โ”€ StockModels.cs # Stock data models for MCP โ”‚ โ””โ”€โ”€ ToolModels.cs # Tool parameter and response models โ”œโ”€โ”€ Services/ โ”‚ โ”œโ”€โ”€ StockApiClient.cs # HTTP client for API communication โ”‚ โ””โ”€โ”€ McpConfigurationService.cs # MCP server configuration โ”œโ”€โ”€ Program.cs # Application entry point and MCP setup โ”œโ”€โ”€ appsettings.json # Application configuration โ”œโ”€โ”€ appsettings.Development.json # Development-specific settings โ”œโ”€โ”€ Dockerfile # Container configuration โ”œโ”€โ”€ build.ps1 # Build automation script โ”œโ”€โ”€ deploy-azure.ps1 # Azure deployment script โ””โ”€โ”€ claude-config-example.md # Claude Desktop configuration guide

๐Ÿ”— Dependencies

Project References

  • HTTP Client - Direct HTTP communication with AiStockTradeApp.Api
  • No direct project references - Loose coupling through HTTP API

NuGet Packages

<PackageReference Include="MCP.NET" />
<PackageReference Include="Microsoft.Extensions.Http" />
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="System.Text.Json" />

๐ŸŒ Tool Usage Examples

Stock Quote Retrieval

{
  "tool": "GetStockQuote",
  "arguments": {
    "symbol": "AAPL"
  }
}

Response:

{
  "symbol": "AAPL",
  "currentPrice": 150.25,
  "change": 2.15,
  "changePercent": 1.45,
  "companyName": "Apple Inc.",
  "lastUpdated": "2025-09-02T14:30:00Z"
}

Historical Data Analysis

{
  "tool": "GetHistoricalData",
  "arguments": {
    "symbol": "GOOGL",
    "days": 30
  }
}
{
  "tool": "SearchStockSymbols",
  "arguments": {
    "query": "Apple"
  }
}

System Health Check

{
  "tool": "GetSystemStatus",
  "arguments": {}
}

๐Ÿ”„ Integration Patterns

HTTP Client Configuration

// StockApiClient.cs
public class StockApiClient
{
    private readonly HttpClient _httpClient;
    
    public StockApiClient(HttpClient httpClient, IConfiguration configuration)
    {
        _httpClient = httpClient;
        var baseUrl = configuration["STOCK_API_BASE_URL"] ?? "http://localhost:5000";
        _httpClient.BaseAddress = new Uri(baseUrl);
    }
    
    public async Task<StockQuote> GetStockQuoteAsync(string symbol)
    {
        var response = await _httpClient.GetAsync($"/api/stocks/quote?symbol={symbol}");
        response.EnsureSuccessStatusCode();
        
        var json = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<StockQuote>(json);
    }
}

MCP Tool Implementation

// StockTradingTools.cs
[McpTool]
public class StockTradingTools
{
    private readonly StockApiClient _apiClient;
    
    [McpToolMethod("GetStockQuote")]
    public async Task<object> GetStockQuoteAsync(
        [McpToolParameter("Stock symbol (e.g., AAPL, GOOGL)")] string symbol)
    {
        try
        {
            var quote = await _apiClient.GetStockQuoteAsync(symbol.ToUpper());
            return new
            {
                success = true,
                data = quote
            };
        }
        catch (Exception ex)
        {
            return new
            {
                success = false,
                error = ex.Message
            };
        }
    }
}

๐Ÿณ Containerization

Docker Support

FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
WORKDIR /app
EXPOSE 8080

FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
COPY ["AiStockTradeApp.McpServer/AiStockTradeApp.McpServer.csproj", "AiStockTradeApp.McpServer/"]
RUN dotnet restore "AiStockTradeApp.McpServer/AiStockTradeApp.McpServer.csproj"

Docker Compose Integration

# docker-compose.mcp-override.yml
services:
  mcp-server:
    build:
      context: .
      dockerfile: AiStockTradeApp.McpServer/Dockerfile
    environment:
      - STOCK_API_BASE_URL=http://api:80
    ports:
      - "8080:8080"
    depends_on:
      - api

๐Ÿงช Testing

Manual Testing

# Test with curl (HTTP mode)
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -d '{"method": "tools/call", "params": {"name": "GetStockQuote", "arguments": {"symbol": "AAPL"}}}'

Integration Testing

[Fact]
public async Task GetStockQuote_ValidSymbol_ReturnsData()
{
    // Arrange
    var tools = new StockTradingTools(_mockApiClient);
    
    // Act
    var result = await tools.GetStockQuoteAsync("AAPL");
    
    // Assert
    result.Should().NotBeNull();
}

๐Ÿ”’ Security Considerations

Network Security

  • HTTPS enforcement - Production API communication
  • Input validation - All tool parameters validated
  • Error handling - No sensitive information exposure
  • Rate limiting - Client-side request throttling

Authentication

  • API key management - Secure credential handling
  • Environment variables - Configuration security
  • No direct database access - API-mediated data access

โ˜๏ธ Azure Deployment

Azure Container Apps

# Deploy to Azure Container Apps
.\deploy-azure.ps1 -ResourceGroupName "stock-trading-rg" -Location "East US"

Environment Configuration

{
  "environmentVariables": [
    {
      "name": "STOCK_API_BASE_URL",
      "value": "https://your-api.azurewebsites.net"
    },
    {
      "name": "ASPNETCORE_ENVIRONMENT",
      "value": "Production"
    }
  ]
}

๐Ÿ”ง Troubleshooting

Common Issues

API Connection Problems
# Test API connectivity
curl $STOCK_API_BASE_URL/health

# Check environment variables
echo $STOCK_API_BASE_URL
MCP Client Issues
  • STDIO communication - Ensure proper command configuration
  • Path resolution - Use absolute paths in MCP client config
  • Environment variables - Verify all required variables are set
Tool Execution Errors
  • Parameter validation - Check tool parameter formats
  • API rate limits - Monitor external API quotas
  • Network connectivity - Test HTTP client connectivity

๐Ÿ“Š Usage Analytics

Logging and Monitoring

// Program.cs - Logging configuration
builder.Services.AddLogging(logging =>
{
    logging.AddConsole();
    logging.AddApplicationInsights();
});

Performance Metrics

  • Tool execution time - Response time monitoring
  • API call frequency - Usage pattern analysis
  • Error rates - Tool failure tracking
  • Client connections - MCP client usage statistics

๐Ÿค External AI Integration

Supported AI Clients

  • Claude Desktop - Full MCP protocol support
  • ChatGPT with MCP - Tool-based integration
  • Custom MCP clients - Standard protocol compliance
  • Development tools - MCP testing utilities

Usage Scenarios

  • Investment research - AI-powered stock analysis
  • Portfolio management - Automated portfolio optimization
  • Market monitoring - Real-time data access for AI agents
  • Trading automation - AI-driven trading decisions
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

Version Downloads Last Updated
1.0.0-beta.15 253 9/4/2025
1.0.0-beta.14 193 9/4/2025
1.0.0-beta.13 200 9/4/2025
1.0.0-beta.12 197 9/4/2025
1.0.0-beta.11 201 9/4/2025
1.0.0-beta.10 211 9/4/2025
1.0.0-beta.9 189 9/2/2025
1.0.0-beta.8 182 9/2/2025
1.0.0-beta.7 182 9/2/2025
1.0.0-beta.6 179 9/2/2025
1.0.0-beta.5 185 9/2/2025
1.0.0-beta.4 184 9/2/2025
1.0.0-beta.3 195 9/2/2025
1.0.0-beta.2 185 9/2/2025
1.0.0-beta.1 186 9/2/2025
1.0.0-beta 190 9/2/2025