### Run MCP Command Example Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/REFACTORING.md Execute a comprehensive example that demonstrates handler registration, command execution, response handling, and the benefits of the new architecture. ```csharp await McpCommandExample.RunExampleAsync(); ``` -------------------------------- ### Run the Application Source: https://github.com/kerryjiang/supersocket/blob/master/samples/LiveChat/README.md Execute the .NET application to start the backend server. ```bash dotnet run ``` -------------------------------- ### Build Angular Frontend Source: https://github.com/kerryjiang/supersocket/blob/master/samples/LiveChat/README.md Navigate to the ClientApp directory and install dependencies, then build the Angular project. ```bash cd ClientApp npm install npm run build cd .. ``` -------------------------------- ### Running the Console Echo Server Source: https://github.com/kerryjiang/supersocket/blob/master/samples/ConsoleEchoServer/README.md Navigate to the sample directory and run the .NET application to start the console echo server. ```bash cd samples/ConsoleEchoServer dotnet run ``` -------------------------------- ### Example WebSocket Session Source: https://github.com/kerryjiang/supersocket/blob/master/samples/LiveChat/README.md Connect to the WebSocket server and send chat commands for joining and messaging. ```javascript // Connect to WebSocket (HTTP only for development) const ws = new WebSocket('ws://localhost:4040'); // Join chat ws.send('CON Alice'); // Send message ws.send('MSG Hello everyone!'); ``` ```javascript // Connect to WebSocket const ws = new WebSocket('ws://localhost:4040'); // Join chat ws.send('CON Alice'); // Send message ws.send('MSG Hello everyone!'); ``` -------------------------------- ### MCP Client Configuration for Stdio Server Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpStdioServer/README.md Example JSON configuration for an MCP client to spawn and manage this stdio server. ```json { "mcpServers": { "supersocket-mcp": { "command": "dotnet", "args": ["run", "--project", "/path/to/McpStdioServer"], "cwd": "/path/to/McpStdioServer" } } } ``` -------------------------------- ### Basic HTTP Keep-Alive Server Setup Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.Http/README.md Demonstrates how to configure and run a basic HTTP server with Keep-Alive support using SuperSocket. ```APIDOC ## Basic HTTP Keep-Alive Server ### Description This example shows how to set up a SuperSocket host with HTTP Keep-Alive support, handling incoming requests and sending JSON responses. ### Method `Host.CreateDefaultBuilder().AsSuperSocketHostBuilder().UsePackageHandler(...).ConfigureSuperSocket(...).Build().RunAsync()` ### Code Example ```csharp using SuperSocket.Http; var hostBuilder = Host.CreateDefaultBuilder() .AsSuperSocketHostBuilder() .UsePackageHandler(async (session, request) => { // Use extension methods for easy response handling await session.SendJsonResponseAsync( $"{{\"path\": \"{request.Path}\", \"keepAlive\": {request.KeepAlive}}}" ); }) .ConfigureSuperSocket(options => { options.Name = "HttpKeepAliveServer"; options.Listeners = new[] { new ListenOptions { Ip = "Any", Port = 8080 } }; }); await hostBuilder.Build().RunAsync(); ``` ``` -------------------------------- ### Stdio Protocol Example Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpStdioServer/README.md Illustrates the difference between TCP/HTTP style and stdio style message framing for MCP communication. ```json Content-Length: 123 Content-Type: application/json {"jsonrpc": "2.0", "method": "initialize", ...} ``` ```json {"jsonrpc": "2.0", "method": "initialize", ...} {"jsonrpc": "2.0", "method": "initialized"} ``` -------------------------------- ### Console Echo Server Usage Example Source: https://github.com/kerryjiang/supersocket/blob/master/samples/ConsoleEchoServer/README.md Illustrates typical interactions with the console echo server, including command input and server responses. ```text Console Echo Server starting... This server reads from stdin and writes to stdout. Type commands and press Enter. Type 'quit' to exit. ---------------------------------------- Welcome to Console Echo Server! Type 'quit' to exit, 'help' for commands. help Available commands: help - Show this help message time - Show current time echo - Echo back the message quit/exit - Close the server echo Hello World Echo: Hello World time Current time: 2025-10-03 14:30:15 quit Server shutting down... ``` -------------------------------- ### Basic HTTP Keep-Alive Server Setup Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.Http/README.md Sets up a SuperSocket host with HTTP Keep-Alive support. Use this to handle multiple HTTP requests over a single connection efficiently. ```csharp using SuperSocket.Http; var hostBuilder = Host.CreateDefaultBuilder() .AsSuperSocketHostBuilder() .UsePackageHandler(async (session, request) => { // Use extension methods for easy response handling await session.SendJsonResponseAsync( $"{{\"path\": \"{request.Path}\", \"keepAlive\": {request.KeepAlive}}}" ); }) .ConfigureSuperSocket(options => { options.Name = "HttpKeepAliveServer"; options.Listeners = new[] { new ListenOptions { Ip = "Any", Port = 8080 } }; }); await hostBuilder.Build().RunAsync(); ``` -------------------------------- ### Program.cs for appsettings.json Configuration Source: https://context7.com/kerryjiang/supersocket/llms.txt The `Program.cs` file for a server that reads listener configurations directly from `appsettings.json`. This simplifies server setup by externalizing configuration. ```csharp // Program.cs — builder reads listeners automatically from appsettings.json var host = SuperSocketHostBuilder.Create(args) .UsePackageHandler(async (s, p) => await s.SendAsync(Encoding.UTF8.GetBytes(p.Text + "\r\n"))) .ConfigureLogging((ctx, logging) => logging.AddConsole()) .Build(); await host.RunAsync(); ``` -------------------------------- ### Configure and Run SuperSocket MCP HTTP Server Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpHttpServer/README.md Example C# code for setting up a SuperSocket MCP server with HTTP support. It registers tools and handles incoming HTTP requests. ```csharp using SuperSocket.MCP; using SuperSocket.Server.Host; var host = SuperSocketHostBuilder.Create(args) .UsePackageHandler(async (session, request) => { var mcpServer = new McpHttpServer(logger, serverInfo); // Register tools mcpServer.RegisterTool("echo", new EchoToolHandler()); // Handle HTTP request await mcpServer.HandleHttpRequestAsync(request, session); }) .ConfigureSuperSocket(options => { options.Name = "McpHttpServer"; options.AddListener(new ListenOptions { Ip = "Any", Port = 8080 }); }) .Build(); await host.RunAsync(); ``` -------------------------------- ### Math Tool JSON Request Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpStdioServer/README.md Example JSON request to perform an addition operation using the math tool. ```json {"method": "tools/call", "params": {"name": "math", "arguments": {"operation": "add", "a": 5, "b": 3}}} ``` -------------------------------- ### Test Capabilities Endpoint Source: https://github.com/kerryjiang/supersocket/blob/master/test/SuperSocket.Tests/Mcp/HTTP_TEST_PLAN.md Use this command to retrieve server capabilities by sending a GET request to the /mcp/capabilities endpoint. ```bash curl http://localhost:8080/mcp/capabilities ``` -------------------------------- ### TCP Client Connection with EasyClient Source: https://context7.com/kerryjiang/supersocket/llms.txt Establishes a TCP client connection to a SuperSocket server using EasyClient. This example demonstrates connecting, receiving packages, and closing the connection. ```csharp using System.Net; using SuperSocket.Client; using SuperSocket.ProtoBase; // TCP client using the same MyPackage / MyPackageFilter from the server var client = new EasyClient(new MyPackageFilter()).AsClient(); var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 5000)); if (!connected) { Console.WriteLine("Connection failed"); return; } Console.WriteLine("Connected. Waiting for packages..."); while (true) { var package = await client.ReceiveAsync(); if (package == null) { Console.WriteLine("Server closed the connection"); break; } Console.WriteLine($"Received: Seq={package.Sequence} Body={package.Body}"); } await client.CloseAsync(); ``` -------------------------------- ### Basic TCP MCP Server Setup Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/USAGE.md Configures and builds a basic TCP MCP server using SuperSocketHostBuilder. It registers MCP commands and sets up basic server configuration and logging. ```csharp using SuperSocket.MCP.Extensions; using SuperSocket.MCP.Models; using SuperSocket.Server.Host; var serverInfo = new McpServerInfo { Name = "MyMcpServer", Version = "1.0.0" }; var host = SuperSocketHostBuilder.Create() .UseMcpCommands(serverInfo) // This configures all MCP commands .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary { { "serverOptions:name", "McpServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", "8080" } }); }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .Build(); await host.RunAsync(); ``` -------------------------------- ### HTTP MCP Server Setup Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/USAGE.md Sets up an HTTP MCP server using SuperSocketHostBuilder. It uses the same command registration as TCP servers but with HTTP-specific message and pipeline filter types. ```csharp using SuperSocket.MCP.Extensions; using SuperSocket.MCP.Models; using SuperSocket.Server.Host; var serverInfo = new McpServerInfo { Name = "MyMcpHttpServer", Version = "1.0.0" }; var host = SuperSocketHostBuilder.Create() .UseMcpCommands(serverInfo) // Same command registration .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary { { "serverOptions:name", "McpHttpServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", "8080" } }); }) .Build(); await host.RunAsync(); ``` -------------------------------- ### Echo Tool JSON Request Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpStdioServer/README.md Example JSON request to invoke the echo tool with a message. ```json {"method": "tools/call", "params": {"name": "echo", "arguments": {"message": "Hello!"}}} ``` -------------------------------- ### MCP Stdio Server Setup Source: https://context7.com/kerryjiang/supersocket/llms.txt Configure a SuperSocket server to use stdin/stdout for communication, suitable for AI agent subprocesses. This replaces the network listener with `UseConsole()` and registers MCP commands. ```csharp using SuperSocket.MCP; using SuperSocket.MCP.Abstractions; using SuperSocket.MCP.Commands; using SuperSocket.MCP.Extensions; using SuperSocket.MCP.Models; using SuperSocket.Server; using SuperSocket.Server.Host; using SuperSocket.Command; using Microsoft.Extensions.DependencyInjection; var host = SuperSocketHostBuilder.Create() .UseConsole() // stdio transport — no TCP listener needed .UseCommand(commandOptions => { commandOptions.AddCommand(); commandOptions.AddCommand(); commandOptions.AddCommand(); commandOptions.AddCommand(); commandOptions.AddCommand(); commandOptions.AddCommand(); }) .ConfigureServices((ctx, services) => { services.AddSingleton(); services.AddSingleton(new McpServerInfo { Name = "My Stdio MCP Server", Version = "1.0.0", ProtocolVersion = "2024-11-05" }); // Register tool handlers in DI for injection into commands services.AddSingleton(); }) .Build(); await host.RunAsync(); // Spawn this process from an MCP client; it speaks JSON-RPC 2.0 over stdin/stdout ``` -------------------------------- ### Basic SSE Client JavaScript Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.Http/README.md A client-side JavaScript example using the EventSource API to connect to an SSE endpoint, handle messages, custom events, and errors. ```javascript const eventSource = new EventSource('/events'); eventSource.onopen = function(event) { console.log('SSE connection opened'); }; eventSource.onmessage = function(event) { console.log('Message:', event.data, 'ID:', event.lastEventId); }; eventSource.addEventListener('custom-type', function(event) { console.log('Custom event:', event.data); }); eventSource.onerror = function(event) { console.error('SSE error:', event); }; ``` -------------------------------- ### Server Capabilities Discovery Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpHttpServer/README.md Retrieve information about the server's capabilities by making a GET request to the `/mcp/capabilities` endpoint. ```APIDOC ## GET /mcp/capabilities ### Description Discover the capabilities supported by the SuperSocket MCP server. ### Method GET ### Endpoint /mcp/capabilities ### Response #### Success Response (200) - **Body**: JSON object detailing server capabilities. ``` -------------------------------- ### File Read Tool JSON Request Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpStdioServer/README.md Example JSON request to read a local text file using the read_file tool. ```json {"method": "tools/call", "params": {"name": "read_file", "arguments": {"path": "/path/to/file.txt"}}} ``` -------------------------------- ### Implement MCP TCP Server with Tool Handlers Source: https://context7.com/kerryjiang/supersocket/llms.txt Utilize McpPipelineFilter and McpMessage for MCP over TCP. Register tools and resources using IMcpToolHandler and IMcpResourceHandler. The example includes an EchoToolHandler. ```csharp using SuperSocket.MCP; using SuperSocket.MCP.Abstractions; using SuperSocket.MCP.Extensions; using SuperSocket.MCP.Models; using SuperSocket.Server; using SuperSocket.Server.Abstractions; using SuperSocket.Server.Host; var host = SuperSocketHostBuilder.Create(args) .UsePackageHandler(async (IAppSession session, McpMessage message) => { var serverInfo = new McpServerInfo { Name = "Demo MCP Server", Version = "1.0.0", ProtocolVersion = "2024-11-05" }; var mcpServer = new McpServer(null, serverInfo); mcpServer.RegisterTool("echo", new EchoToolHandler()); var response = await mcpServer.HandleMessageAsync(message, session); if (response != null) await session.SendMcpMessageAsync(response); }) .ConfigureSuperSocket(o => { o.Name = "McpServer"; o.AddListener(new ListenOptions { Ip = "Any", Port = 3000 }); }) .Build(); await host.RunAsync(); // Tool handler implementation public class EchoToolHandler : IMcpToolHandler { public Task GetToolDefinitionAsync() => Task.FromResult(new McpTool { Name = "echo", Description = "Echo back the input", InputSchema = new { type = "object", properties = new { message = new { type = "string" } }, required = new[] { "message" } } }); public Task ExecuteAsync(Dictionary args) { var msg = args.TryGetValue("message", out var v) ? v?.ToString() : ""; return Task.FromResult(new McpToolResult { Content = new List { new McpContent { Type = "text", Text = $"Echo: {msg}" } } }); } } ``` -------------------------------- ### Command Filter for Logging Source: https://context7.com/kerryjiang/supersocket/llms.txt Implement synchronous `CommandFilter` to add pre/post execution logic like logging or authorization to commands. This example defines a filter that logs the execution of commands. ```csharp using SuperSocket.Command; using SuperSocket.Server.Abstractions.Session; using SuperSocket.ProtoBase; // A filter that logs before and after every command executes public class LoggingCommandFilter : CommandFilterAttribute { public override void OnCommandExecuting(CommandExecutingContext commandContext) { Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Executing command: {commandContext.CurrentCommand.GetType().Name}"); } public override void OnCommandExecuted(CommandExecutingContext commandContext) { Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Executed command: {commandContext.CurrentCommand.GetType().Name}"); } } // Apply the filter to a specific command [Command("add")] [LoggingCommandFilter] public class ADD : IAsyncCommand { public async ValueTask ExecuteAsync( IAppSession session, StringPackageInfo package, CancellationToken cancellationToken) { var sum = package.Parameters.Select(int.Parse).Sum(); await session.SendAsync(Encoding.UTF8.GetBytes(sum + "\r\n"), cancellationToken); } } ``` -------------------------------- ### Custom Server-Level Middleware Source: https://context7.com/kerryjiang/supersocket/llms.txt Implement custom server-level middleware to handle cross-cutting concerns like rate limiting or authentication for all received packages. This example includes a background task to periodically broadcast the server time to all connected WebSocket sessions. ```csharp using SuperSocket.Server.Abstractions.Middleware; using SuperSocket.Server.Abstractions.Session; using SuperSocket.WebSocket.Server; // Custom middleware that tracks message counts and periodically broadcasts to all sessions public class ServerPushMiddleware : MiddlewareBase { private ISessionContainer _sessions; public override void Start(IServer server) { _sessions = server.ServiceProvider.GetService(); // Start a background push loop _ = Task.Run(async () => { while (true) { await Task.Delay(5000); var sessions = _sessions?.GetSessions().ToList(); if (sessions != null) { foreach (var s in sessions.OfType()) await s.SendAsync($"Server time: {DateTime.Now:HH:mm:ss}"); } } }); } } var host = WebSocketHostBuilder.Create(args) .UseWebSocketMessageHandler(async (session, msg) => { if (msg.Message == "ACK") Console.WriteLine($"{session.SessionID} acknowledged"); await Task.CompletedTask; }) .UseInProcSessionContainer() .UseMiddleware() .Build(); await host.RunAsync(); ``` -------------------------------- ### Build and Run MCP Stdio Server Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpStdioServer/README.md Commands to build and run the MCP Stdio Server sample. ```bash cd samples/McpStdioServer dotnet build dotnet run ``` -------------------------------- ### Configure Connection Options for EasyClient Source: https://context7.com/kerryjiang/supersocket/llms.txt Set buffer sizes, max package length, and timeouts for network connections. Pass these options when constructing EasyClient or configure at the server level. ```csharp using SuperSocket.Client; using SuperSocket.Connection; using SuperSocket.ProtoBase; using System.Net; var options = new ConnectionOptions { MaxPackageLength = 4 * 1024 * 1024, // 4 MB max package ReceiveBufferSize = 32 * 1024, // 32 KB receive buffer SendBufferSize = 32 * 1024, // 32 KB send buffer ReceiveTimeout = 30_000, // 30 s receive timeout (ms) SendTimeout = 10_000 // 10 s send timeout (ms) }; var client = new EasyClient(new MyPackageFilter(), options).AsClient(); await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 5000)); ``` -------------------------------- ### Initialize WebSocket Connection and Event Handlers Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpWebSocketServer/test-client.html Sets up a WebSocket connection to the server with 'mcp' subprotocol. Handles connection opening, message reception, closure, and errors. Automatically initializes the MCP session upon successful connection. ```javascript let ws = null; let messageId = 1; let isInitialized = false; const status = document.getElementById('status'); const messages = document.getElementById('messages'); const connectBtn = document.getElementById('connectBtn'); const sendBtn = document.getElementById('sendBtn'); const messageInput = document.getElementById('messageInput'); const serverUrl = document.getElementById('serverUrl'); function addMessage(content, type = 'received') { const div = document.createElement('div'); div.className = `message ${type} `; div.innerHTML = `${new Date().toLocaleTimeString()} - ${content} `; messages.appendChild(div); messages.scrollTop = messages.scrollHeight; } function updateStatus(connected) { status.textContent = connected ? 'Connected to MCP WebSocket Server' : 'Disconnected'; status.className = `status ${connected ? 'connected' : 'disconnected'} `; connectBtn.textContent = connected ? 'Disconnect' : 'Connect'; connectBtn.className = connected ? 'btn-danger' : 'btn-primary'; sendBtn.disabled = !connected; document.getElementById('initializeBtn').disabled = !connected; document.getElementById('listToolsBtn').disabled = !connected || !isInitialized; // Tool buttons document.getElementById('echoBtn').disabled = !connected || !isInitialized; document.getElementById('mathBtn').disabled = !connected || !isInitialized; document.getElementById('timeBtn').disabled = !connected || !isInitialized; document.getElementById('webinfoBtn').disabled = !connected || !isInitialized; } function connect() { if (ws && ws.readyState === WebSocket.OPEN) { ws.close(); return; } try { ws = new WebSocket(serverUrl.value, ['mcp'] ); ws.onopen = () => { updateStatus(true); addMessage('Connected to MCP WebSocket server', 'received'); }; ws.onmessage = (event) => { try { const data = JSON.parse(event.data); addMessage( `Received: ${JSON.stringify(data, null, 2)}` , 'received'); // Check if this is an initialize response if (data.result && data.result.protocolVersion) { isInitialized = true; updateStatus(true); addMessage('MCP session initialized successfully!', 'received'); } } catch (e) { addMessage( `Received (raw): ${event.data} ` , 'received'); } }; ws.onclose = () => { updateStatus(false); isInitialized = false; addMessage('Disconnected from server', 'error'); }; ws.onerror = (error) => { addMessage( `WebSocket error: ${error} ` , 'error'); }; } catch (e) { addMessage( `Connection error: ${e.message} ` , 'error'); } } ``` -------------------------------- ### Legacy vs New MCP Server Implementation Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/USAGE.md Compares the legacy approach of instantiating `McpServer` directly with the new SuperSocket host builder pattern. The new approach is recommended for modern implementations. ```csharp // Legacy: // var mcpServer = new McpServer(logger, serverInfo); // mcpServer.RegisterTool("echo", new EchoToolHandler()); // New: var host = SuperSocketHostBuilder.Create() .UseMcpCommands(serverInfo) .Build(); var handlerRegistry = host.Services.GetRequiredService(); handlerRegistry.RegisterTool("echo", new EchoToolHandler()); ``` -------------------------------- ### Execute MCP Command Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/REFACTORING.md Instantiate and execute an MCP command, such as InitializeCommand. This demonstrates the basic flow of command execution within the refactored architecture. ```csharp var command = new InitializeCommand(logger, handlerRegistry, serverInfo); await command.ExecuteAsync(session, message, cancellationToken); ``` -------------------------------- ### Test SSE Connection Source: https://github.com/kerryjiang/supersocket/blob/master/test/SuperSocket.Tests/Mcp/HTTP_TEST_PLAN.md This command tests the Server-Sent Events (SSE) connection by sending a GET request to the /mcp/events endpoint with the appropriate Accept header. ```bash curl -N -H "Accept: text/event-stream" http://localhost:8080/mcp/events ``` -------------------------------- ### Implement IAsyncCommand for Request Dispatch Source: https://context7.com/kerryjiang/supersocket/llms.txt Define commands by implementing `IAsyncCommand` and decorating with `[Command("key")]`. Commands are registered individually or by scanning an assembly. Ensure the package info type matches the command's generic parameter. ```csharp using SuperSocket.Command; using SuperSocket.ProtoBase; using SuperSocket.Server.Abstractions.Session; using System.Text; // Each command maps to a keyword sent by the client (e.g., "ADD 1 2 3\r\n") [Command("add")] public class ADD : IAsyncCommand { public async ValueTask ExecuteAsync( IAppSession session, StringPackageInfo package, CancellationToken cancellationToken) { var result = package.Parameters .Select(p => int.Parse(p)) .Sum(); await session.SendAsync( Encoding.UTF8.GetBytes(result.ToString() + "\r\n"), cancellationToken); } } [Command("mult")] public class MULT : IAsyncCommand { public async ValueTask ExecuteAsync(IAppSession session, StringPackageInfo package, CancellationToken cancellationToken) { var result = package.Parameters.Select(int.Parse).Aggregate(1, (a, b) => a * b); await session.SendAsync(Encoding.UTF8.GetBytes(result + "\r\n"), cancellationToken); } } // Registration in host builder var host = SuperSocketHostBuilder.Create(args) .UseCommand(commandOptions => { commandOptions.AddCommand(); commandOptions.AddCommand(); // Or scan an entire assembly: // commandOptions.AddCommandAssembly(typeof(ADD).Assembly); }) .ConfigureAppConfiguration((ctx, config) => config.AddInMemoryCollection(new Dictionary { { "serverOptions:name", "CommandServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", "4040" } })) .ConfigureLogging((ctx, logging) => logging.AddConsole()) .Build(); await host.RunAsync(); // Client sends: "ADD 1 2 3\r\n" → server replies: "6\r\n" ``` -------------------------------- ### Test Tool Execution via HTTP POST Source: https://github.com/kerryjiang/supersocket/blob/master/test/SuperSocket.Tests/Mcp/HTTP_TEST_PLAN.md This command demonstrates testing tool execution by sending a POST request to the /mcp endpoint with a 'tools/call' method and parameters. ```bash curl -X POST http://localhost:8080/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "echo", "arguments": { "message": "Hello from HTTP!" } } }' ``` -------------------------------- ### SOCKS5 Proxy Client Connection Source: https://context7.com/kerryjiang/supersocket/llms.txt Routes client traffic through a SOCKS5 proxy by configuring the client.Proxy property with a Socks5Connector. This example shows how to specify proxy endpoint, username, and password. ```csharp using System.Net; using SuperSocket.Client; using SuperSocket.Client.Proxy; using SuperSocket.ProtoBase; var client = new EasyClient(new LinePipelineFilter()).AsClient(); // Route through an authenticated SOCKS5 proxy client.Proxy = new Socks5Connector( new DnsEndPoint("proxy.example.com", 1080), username: "user", password: "pass"); var connected = await client.ConnectAsync(new DnsEndPoint("target.example.com", 4040)); if (!connected) { Console.Error.WriteLine("Proxy connection failed"); return; } var package = await client.ReceiveAsync(); Console.WriteLine(package?.Text); await client.CloseAsync(); ``` -------------------------------- ### Configure HTTP MCP Server Host Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Sets up the SuperSocket host with HTTP transport, registers an Echo tool, and configures the listener. Ensure ILogger and McpServerInfo are correctly provided. ```csharp using SuperSocket.MCP; using SuperSocket.Server.Host; var host = SuperSocketHostBuilder.Create(args) .UsePackageHandler(async (session, request) => { var logger = session.Server.ServiceProvider.GetService(typeof(ILogger)) as ILogger; var serverInfo = new McpServerInfo { Name = "My HTTP MCP Server", Version = "1.0.0", ProtocolVersion = "2024-11-05" }; var mcpServer = new McpHttpServer(logger!, serverInfo); // Register your tools mcpServer.RegisterTool("echo", new EchoToolHandler()); // Handle HTTP request await mcpServer.HandleHttpRequestAsync(request, session); }) .ConfigureSuperSocket(options => { options.Name = "McpHttpServer"; options.AddListener(new ListenOptions { Ip = "Any", Port = 8080 }); }) .Build(); await host.RunAsync(); ``` -------------------------------- ### List Available Tools Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpWebSocketServer/test-client.html Sends a 'tools/list' JSON-RPC message to the server to retrieve a list of available tools. ```javascript function listTools() { const message = { jsonrpc: "2.0", id: messageId++, method: "tools/list" }; sendMessage(message); } ``` -------------------------------- ### HttpResponse Class Usage Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.Http/README.md Shows how to construct and prepare an HTTP response object. ```APIDOC ## HttpResponse Class ### Description This section details how to create and configure an `HttpResponse` object, including setting status code, content type, body, and keep-alive status, before converting it to bytes for sending. ### Method `new HttpResponse(statusCode, statusDescription)` and `response.SetContentType(contentType)`, `response.ToBytes()` ### Code Example ```csharp var response = new HttpResponse(200, "OK"); response.SetContentType("application/json"); response.Body = "{\"message\": \"Hello World\"}"; response.KeepAlive = true; // Convert to bytes for sending byte[] responseBytes = response.ToBytes(); ``` ``` -------------------------------- ### Connect to WebSocket MCP Server Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Establishes a WebSocket connection with the 'mcp' sub-protocol and sends an initial 'initialize' message. Handles incoming JSON-RPC responses. ```javascript // Connect with WebSocket sub-protocol "mcp" const ws = new WebSocket('ws://localhost:8080', ['mcp']); ws.onopen = () => { // Send initialize message ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "Browser Client", version: "1.0.0" } } })); }; ws.onmessage = (event) => { const response = JSON.parse(event.data); console.log('MCP Response:', response); }; ``` -------------------------------- ### ASP.NET Core Integration with SuperSocket Source: https://context7.com/kerryjiang/supersocket/llms.txt Embeds SuperSocket into an ASP.NET Core application using AsSuperSocketHostBuilder. The session container is accessible from Minimal API or MVC endpoints via DI. Includes an example REST endpoint to list active sessions. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; using SuperSocket.Server; using SuperSocket.Server.Host; using SuperSocket.Server.Abstractions.Session; using SuperSocket.ProtoBase; using System.Text; var builder = WebApplication.CreateBuilder(args); builder.Host .AsSuperSocketHostBuilder() .UsePipelineFilter() .UsePackageHandler(async (session, package) => await session.SendAsync(Encoding.UTF8.GetBytes(package.Text + "\r\n"))) .UseInProcSessionContainer() .AsMinimalApiHostBuilder() .ConfigureHostBuilder(); var app = builder.Build(); // REST endpoint to list all active socket sessions app.MapGet("/api/sessions", ([FromServices] ISessionContainer sessions) => Results.Json(sessions.GetSessions().Select(s => new { s.SessionID, s.RemoteEndPoint }))); await app.RunAsync(); // GET http://localhost:5000/api/sessions → JSON array of active socket clients ``` -------------------------------- ### Configure TLS Listener via appsettings.json Source: https://context7.com/kerryjiang/supersocket/llms.txt Set up a TLS-enabled listener in `appsettings.json` by specifying certificate file path, password, and enabled SSL protocols. This configuration is automatically applied by the builder. ```json // appsettings.tls.json — TLS listener { "serverOptions": { "name": "TlsServer", "listeners": [ { "ip": "Any", "port": 4040, "authenticationOptions": { "certificateOptions": { "filePath": "supersocket.pfx", "password": "supersocket" }, "enabledSslProtocols": "Tls12" } } ] } } ``` -------------------------------- ### Build a TCP Server with Line Protocol Source: https://context7.com/kerryjiang/supersocket/llms.txt Use `SuperSocketHostBuilder.Create` to build a TCP server that handles newline-delimited text packages. The `LinePipelineFilter` and `TextPackageInfo` are used for this purpose. The server echoes received text back to the client. ```csharp using System.Text; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket.Server; using SuperSocket.Server.Abstractions; using SuperSocket.Server.Host; using SuperSocket.ProtoBase; // TextPackageInfo + LinePipelineFilter handle newline-delimited text var host = SuperSocketHostBuilder.Create(args) .UsePackageHandler(async (session, package) => { // Echo the received text back to the client await session.SendAsync(Encoding.UTF8.GetBytes(package.Text + "\r\n")); }) .ConfigureSuperSocket(options => { options.Name = "EchoServer"; options.AddListener(new ListenOptions { Ip = "Any", Port = 4040 }); }) .ConfigureLogging((ctx, logging) => logging.AddConsole()) .Build(); await host.RunAsync(); // Connect with: telnet localhost 4040 // Each line typed is echoed back ``` -------------------------------- ### Registering MCP Handlers Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/USAGE.md Shows how to register custom handlers for MCP tools, resources, and prompts using the `IMcpHandlerRegistry`. This is done after the host is built and requires accessing the service provider. ```csharp // Get the handler registry from DI var handlerRegistry = host.Services.GetRequiredService(); // Register handlers handlerRegistry.RegisterTool("echo", new EchoToolHandler()); handlerRegistry.RegisterResource("file://example", new FileResourceHandler()); handlerRegistry.RegisterPrompt("greeting", new GreetingPromptHandler()); ``` -------------------------------- ### Manual MCP Command Registration Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/USAGE.md Demonstrates manual registration of individual MCP commands using the `UseCommand` configuration. This provides more granular control over which commands are enabled. ```csharp var host = SuperSocketHostBuilder.Create() .ConfigureServices((hostCtx, services) => { services.AddMcpCommandServices(serverInfo); }) .UseCommand((commandOptions) => { // Register individual commands commandOptions.AddCommand(); commandOptions.AddCommand(); commandOptions.AddCommand(); commandOptions.AddCommand(); commandOptions.AddCommand(); commandOptions.AddCommand(); commandOptions.AddCommand(); commandOptions.AddCommand(); }) .Build(); ``` -------------------------------- ### WebSocket Server with Per-Message Compression Source: https://context7.com/kerryjiang/supersocket/llms.txt Build a WebSocket server using WebSocketHostBuilder.Create(). Use UsePerMessageCompression() for RFC 7692 per-message deflate support. The handler receives a WebSocketPackage. ```csharp using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket.WebSocket.Server; var host = WebSocketHostBuilder.Create(args) .UseWebSocketMessageHandler(async (session, message) => { // Echo the WebSocket text frame back to the sender await session.SendAsync(message.Message); }) .UsePerMessageCompression() // RFC 7692 per-message deflate .ConfigureLogging((ctx, logging) => logging.AddConsole()) .Build(); await host.RunAsync(); // Connect with any WebSocket client to ws://localhost:4040 ``` -------------------------------- ### Configure Server Listeners via appsettings.json Source: https://context7.com/kerryjiang/supersocket/llms.txt Define server listeners, including IP addresses and ports, in `appsettings.json`. The `SuperSocketHostBuilder` automatically binds this configuration when `args` are passed to `Create()`. ```json // appsettings.json { "serverOptions": { "name": "TestServer", "listeners": [ { "ip": "Any", "port": 4040 }, { "ip": "Any", "port": 4041 } ] } } ``` -------------------------------- ### IMcpPromptHandler Interface Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Implement this interface to handle prompt-based interactions within the MCP framework. ```APIDOC ## IMcpPromptHandler Implement this interface to create MCP prompts: ```csharp public interface IMcpPromptHandler { Task GetPromptDefinitionAsync(); Task GetPromptAsync(Dictionary? arguments = null); } ``` ### Methods - **GetPromptDefinitionAsync**: Retrieves the definition of the prompt. - **GetPromptAsync**: Retrieves the prompt, optionally with arguments. ``` -------------------------------- ### Configure Stdio Transport for MCP Server Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Use this configuration for the stdio transport, recommended for AI assistants and command-line tools. It sets up the MCP server with specified server information and registers tool handlers. ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket.MCP; using SuperSocket.MCP.Abstractions; using SuperSocket.MCP.Extensions; using SuperSocket.MCP.Models; var host = Host.CreateDefaultBuilder(args) .ConfigureMcp(mcpBuilder => { mcpBuilder .ConfigureServer(serverInfo => { serverInfo.Name = "My MCP Server"; serverInfo.Version = "1.0.0"; serverInfo.ProtocolVersion = "2024-11-05"; }) .AddTool() .AddTool(); }) .Build(); await host.RunAsync(); ``` -------------------------------- ### Migrating HTTP Response Building in SuperSocket Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.Http/README.md Illustrates the migration from manual HTTP response building to using the `SendJsonResponseAsync` extension method for cleaner code. ```csharp // Before .UsePackageHandler(async (s, p) => { var response = "HTTP/1.1 200 OK\r\n" + "Content-Type: application/json\r\n" + "Content-Length: 26\r\n\r\n" + "{\"message\": \"Hello\"}"; await s.SendAsync(Encoding.UTF8.GetBytes(response)); }) // After .UsePackageHandler(async (s, p) => { await s.SendJsonResponseAsync("{\"message\": \"Hello\"}"); }) ``` -------------------------------- ### Directly Test MCP Stdio Server Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpStdioServer/README.md How to test the server directly by piping JSON messages to its standard input. ```bash echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test", "version": "1.0"}}}' | dotnet run ``` -------------------------------- ### Register MCP Command Services Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/REFACTORING.md Register MCP command services using dependency injection helpers. This is the recommended approach for new implementations to integrate with the command pattern. ```csharp services.AddMcpCommandServices(serverInfo); ``` -------------------------------- ### Session Extension Methods for Responses and SSE Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.Http/README.md Explains how to use extension methods on the session object to send HTTP responses and manage SSE streams. ```APIDOC ## Session Extensions ### Description This section describes utility extension methods provided for the session object, enabling easy sending of standard HTTP responses and convenient creation or starting of Server-Sent Events streams. ### Method `session.SendHttpResponseAsync(statusCode, statusDescription, contentType)`, `session.SendJsonResponseAsync(data)`, `session.CreateSSEWriter()`, `session.StartSSEAsync()` ### Code Example ```csharp // Simple responses await session.SendHttpResponseAsync(200, "OK", "text/plain"); await session.SendJsonResponseAsync("{\"status\": \"success\"}"); // SSE operations var sseWriter = session.CreateSSEWriter(); var sseWriter = await session.StartSSEAsync(); // Sends initial headers automatically ``` ``` -------------------------------- ### Run SuperSocket MCP Tests Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Execute the comprehensive test suite for the SuperSocket MCP package using the dotnet test command. ```bash dotnet test test/SuperSocket.MCP.Tests/ ``` -------------------------------- ### Run MCP Server with HTTP Transport Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Execute the MCP server project configured for HTTP communication. ```bash dotnet run --project samples/McpHttpServer/McpHttpServer.csproj ``` -------------------------------- ### EasyClient with TLS Enabled Source: https://context7.com/kerryjiang/supersocket/llms.txt Configures an EasyClient to establish a secure connection using TLS. It sets the SecurityOptions, including enabling TLS 1.2+ and providing a certificate validation callback (for development purposes). ```csharp using System.Net; using System.Security.Authentication; using SuperSocket.Client; using SuperSocket.ProtoBase; var client = new EasyClient(new LinePipelineFilter()).AsClient(); // Enable TLS 1.2+ client.Security = new SecurityOptions { EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13, RemoteCertificateValidationCallback = (sender, cert, chain, errors) => true // dev only }; await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 4040)); while (true) { var p = await client.ReceiveAsync(); if (p == null) break; Console.WriteLine(p.Text); } ``` -------------------------------- ### Run MCP Server with Stdio Transport Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Execute the MCP server project configured for standard input/output communication. ```bash dotnet run --project samples/McpStdioServer/McpStdioServer.csproj ``` -------------------------------- ### Run MCP Server with WebSocket Transport Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Execute the MCP server project configured for WebSocket communication. ```bash dotnet run --project samples/McpWebSocketServer/McpWebSocketServer.csproj ``` -------------------------------- ### Configure Enhanced Socket Client Source: https://github.com/kerryjiang/supersocket/blob/master/releaseNotes/v2.1.0.md Instantiate a SocketConnector to bind to a specific local endpoint or customize socket configurations by overriding the ConfigureSocket method. ```csharp // Bind to specific local endpoint var connector = new SocketConnector(new IPEndPoint(IPAddress.Any, 0)); // Or customize socket configuration public class CustomConnector : SocketConnector { protected override void ConfigureSocket(Socket socket) { base.ConfigureSocket(socket); // Add custom socket options } } ``` -------------------------------- ### Test Basic HTTP POST Request Source: https://github.com/kerryjiang/supersocket/blob/master/test/SuperSocket.Tests/Mcp/HTTP_TEST_PLAN.md Use this command to test sending a basic HTTP POST request with a JSON-RPC 2.0 body to the /mcp endpoint. ```bash curl -X POST http://localhost:8080/mcp \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }' ``` -------------------------------- ### IMcpResourceHandler Interface Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Implement this interface to manage resources that can be read by the MCP server. ```APIDOC ## IMcpResourceHandler Implement this interface to create MCP resources: ```csharp public interface IMcpResourceHandler { Task GetResourceDefinitionAsync(); Task ReadAsync(string uri); } ``` ### Methods - **GetResourceDefinitionAsync**: Retrieves the definition of the resource. - **ReadAsync**: Reads the content of the resource at the specified URI. ``` -------------------------------- ### Call Web Info Tool Source: https://github.com/kerryjiang/supersocket/blob/master/samples/McpWebSocketServer/test-client.html Sends a 'tools/call' JSON-RPC message to invoke the 'webinfo' tool. This tool likely retrieves information about the web environment. ```javascript function callWebInfoTool() { const message = { jsonrpc: "2.0", id: messageId++, method: "tools/call", params: { name: "webinfo", arguments: {} } }; sendMessage(message); } ``` -------------------------------- ### Implement Echo Tool Handler Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Provides a concrete implementation for an MCP tool handler named 'echo'. Defines the tool's input schema and the logic to echo back a message. ```csharp public class EchoToolHandler : IMcpToolHandler { public Task GetToolDefinitionAsync() { return Task.FromResult(new McpTool { Name = "echo", Description = "Echo back the input message", InputSchema = new { type = "object", properties = new { message = new { type = "string", description = "Message to echo back" } }, required = new[] { "message" } } }); } public Task ExecuteAsync(Dictionary arguments) { var message = arguments.TryGetValue("message", out var msg) ? msg.ToString() : "Hello!"; return Task.FromResult(new McpToolResult { Content = new List { new McpContent { Type = "text", Text = $"Echo: {message}" } } }); } } ``` -------------------------------- ### IMcpToolHandler Interface Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Implement this interface to define custom tools that can be registered and executed by the MCP server. ```APIDOC ## IMcpToolHandler Implement this interface to create MCP tools: ```csharp public interface IMcpToolHandler { Task GetToolDefinitionAsync(); Task ExecuteAsync(Dictionary arguments); } ``` ### Methods - **GetToolDefinitionAsync**: Retrieves the definition of the tool. - **ExecuteAsync**: Executes the tool with the provided arguments. ``` -------------------------------- ### Server-Sent Events Stream Handling Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.Http/README.md Illustrates how to handle SSE requests, send events, and manage the SSE stream lifecycle. ```APIDOC ## Server-Sent Events Stream ### Description This example demonstrates how to handle requests for Server-Sent Events, initiate an SSE stream, send various types of events, and manage the stream's heartbeat. ### Method `session.StartSSEAsync()` and `sseWriter.SendEventAsync()`, `sseWriter.SendJsonEventAsync()`, `sseWriter.StartHeartbeatAsync()` ### Code Example ```csharp .UsePackageHandler(async (session, request) => { if (request.Path == "/events" && request.IsSSERequest()) { // Start SSE stream var sseWriter = await session.StartSSEAsync(); // Send events await sseWriter.SendEventAsync("Hello SSE!", "greeting"); await sseWriter.SendJsonEventAsync("{\"type\": \"data\", \"value\": 42}"); // Start automatic heartbeat _ = sseWriter.StartHeartbeatAsync(cancellationToken); // Send more events as needed... await sseWriter.SendCloseEventAsync(); } else { await session.SendHttpResponseAsync(200, "Use /events for SSE", "text/plain"); } }) ``` ``` -------------------------------- ### Define an MCP Tool Handler Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Implement the IMcpToolHandler interface to create custom tools that can be registered and executed by the MCP server. Requires defining the tool's metadata and its execution logic. ```csharp public interface IMcpToolHandler { Task GetToolDefinitionAsync(); Task ExecuteAsync(Dictionary arguments); } ``` -------------------------------- ### Define an MCP Prompt Handler Source: https://github.com/kerryjiang/supersocket/blob/master/src/SuperSocket.MCP/README.md Implement the IMcpPromptHandler interface to handle prompt-based interactions within MCP. This includes defining prompt metadata and providing a method to retrieve prompt content, optionally with arguments. ```csharp public interface IMcpPromptHandler { Task GetPromptDefinitionAsync(); Task GetPromptAsync(Dictionary? arguments = null); } ```