File: README.md
SuperSocket
SuperSocket is a high-performance, extensible socket server application framework for .NET. It provides a robust architecture for building custom network communication applications with support for multiple protocols including TCP, UDP, and WebSocket.
- Project homepage: https://www.supersocket.net/
- Documentation: https://docs.supersocket.net/
- License: https://www.apache.org/licenses/LICENSE-2.0
Key features of SuperSocket include:
Flexible Pipeline Architecture:
SuperSocket implements a pipeline-based processing model that allows for efficient handling of incoming data with customizable filters.Protocol Abstraction:
The framework abstracts away low-level socket operations and provides a clean interface for implementing various protocols through pipeline filters. It has built-in support for TCP, UDP, WebSocket, and even custom protocols.Middleware Support:
Extensible middleware system allowing for custom processing of connections and packages.Session Management:
SuperSocket provides comprehensive session handling capabilities, managing connection lifecycles from establishment to termination.Command Handling System:
Command-based processing model to handle client requests efficiently.WebSocket Support:
Full implementation of the WebSocket protocol with extensions like compression.Modern .NET Integration:
SuperSocket is built for modern .NET and integrates seamlessly with the dependency injection, configuration, and logging facilities in the .NET ecosystem.Cross-Platform:
As a .NET library, SuperSocket works across platforms supported by .NET.Client Support:
The framework includes client components for establishing connections to socket servers, including proxy capabilities.High Performance:
SuperSocket is designed for high throughput and low latency with efficient memory usage through buffer pooling and minimal allocations
SuperSocket is suitable for a wide range of applications including:
- Real-time communication systems
- IoT device connectivity
- Game servers
- Chat applications
- and any scenario requiring custom network protocols
Nuget Packages
| Package | MyGet Beta Release | NuGet Stable Release |
|---|---|---|
| SuperSocket.ProtoBase | ||
| SuperSocket.Primitives | ||
| SuperSocket.Connection | ||
| SuperSocket.Kestrel | ||
| SuperSocket.Server | ||
| SuperSocket.Server.Abstractions | ||
| SuperSocket.Command | ||
| SuperSocket.Client | ||
| SuperSocket.Client.Proxy | ||
| SuperSocket.WebSocket | ||
| SuperSocket.WebSocket.Server | ||
| SuperSocket.Udp | ||
| SuperSocket.SerialIO | ||
| SuperSocket.ProtoBuf | ||
| SuperSocket.MessagePack |
Nightly build packages: https://www.myget.org/F/supersocket/api/v3/index.json
SuperSocket 2.0 Roadmap:
- 2025:
- More documents
- Performance test/tuning
- Fix issues of the existing features
- Other features requested by users
File: samples/McpStdioServer/README.md
MCP Stdio Server Sample
This sample demonstrates how to create an MCP (Model Context Protocol) server that communicates over stdio (stdin/stdout) using SuperSocket's new console connection support.
Overview
MCP servers are typically designed to run as subprocesses and communicate via stdio rather than TCP. This is the standard deployment pattern for MCP servers, where:
- MCP clients spawn the server as a subprocess
- Communication happens via stdin/stdout using newline-delimited JSON-RPC messages
- The server process is managed by the client
Key Features
- Stdio Communication: Uses SuperSocket's new
UseConsole()extension for stdio-based communication - Line-based Protocol: Updated
McpPipelineFilterthat processes newline-delimited JSON messages - Command Architecture: Uses SuperSocket's command system for proper MCP message handling
- Tool Implementation: Includes sample tools (echo, math, file reading)
Protocol Changes
Before (TCP/HTTP style):
Content-Length: 123
Content-Type: application/json
{"jsonrpc": "2.0", "method": "initialize", ...}After (Stdio style):
{"jsonrpc": "2.0", "method": "initialize", ...}
{"jsonrpc": "2.0", "method": "initialized"}Available Tools
Echo Tool - Simple echo functionality
json{"method": "tools/call", "params": {"name": "echo", "arguments": {"message": "Hello!"}}}Math Tool - Basic arithmetic operations
json{"method": "tools/call", "params": {"name": "math", "arguments": {"operation": "add", "a": 5, "b": 3}}}File Read Tool - Read local text files
json{"method": "tools/call", "params": {"name": "read_file", "arguments": {"path": "/path/to/file.txt"}}}
Building and Running
cd samples/McpStdioServer
dotnet build
dotnet runUsage as MCP Server
Direct Testing
You can test the server directly by piping JSON messages:
echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test", "version": "1.0"}}}' | dotnet runIntegration with MCP Clients
Configure your MCP client to spawn this server:
{
"mcpServers": {
"supersocket-mcp": {
"command": "dotnet",
"args": ["run", "--project", "/path/to/McpStdioServer"],
"cwd": "/path/to/McpStdioServer"
}
}
}MCP Protocol Flow
- Initialize: Client sends initialization message
- Initialized: Server confirms initialization
- Tool Discovery: Client can query available tools via
tools/list - Tool Execution: Client calls tools via
tools/call - Resource Access: Server can provide resources via
resources/listandresources/read
Implementation Details
Console Connection Integration
- Uses SuperSocket's
UseConsole()extension - Leverages the new
ConsoleConnectionfor stdio communication - Maintains full SuperSocket feature compatibility
Pipeline Filter Optimization
- Simplified from Content-Length headers to line-based JSON
- Better suited for stdio communication patterns
- Handles empty lines and malformed input gracefully
Command-based Architecture
- Uses SuperSocket's command system instead of legacy message handling
- Proper separation of concerns
- Extensible for additional MCP methods
Logging Considerations
The server minimizes logging to stdout to avoid interfering with the MCP protocol. Important considerations:
- Logs warning level and above to stderr
- Normal MCP communication happens on stdout
- Debug information should be logged to files if needed
Error Handling
The server includes comprehensive error handling for:
- Malformed JSON messages
- Invalid tool parameters
- File system access errors
- Network/stdio communication issues
All errors are returned as proper JSON-RPC error responses according to the MCP specification.
File: samples/McpHttpServer/README.md
SuperSocket MCP HTTP Support
SuperSocket MCP now supports HTTP transport in addition to the original TCP transport with Content-Length headers. This enables easier integration with web applications and provides Server-Sent Events (SSE) support for real-time notifications.
Features
- HTTP POST: Send MCP JSON-RPC requests via HTTP POST to
/mcp - Server-Sent Events: Connect to
/mcp/eventsfor real-time notifications - Capabilities Endpoint: GET
/mcp/capabilitiesto discover server capabilities - Backward Compatibility: Original TCP transport still works unchanged
Usage
HTTP POST Requests
Send MCP JSON-RPC requests to the /mcp endpoint:
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "echo",
"arguments": {
"message": "Hello from HTTP!"
}
}
}'Server-Sent Events
Connect to the SSE endpoint for real-time notifications:
const eventSource = new EventSource('http://localhost:8080/mcp/events');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
eventSource.addEventListener('notification', function(event) {
const notification = JSON.parse(event.data);
console.log('Notification:', notification);
});Capabilities
Check server capabilities:
curl http://localhost:8080/mcp/capabilitiesExample Server
using SuperSocket.MCP;
using SuperSocket.Server.Host;
var host = SuperSocketHostBuilder.Create<McpHttpRequest, McpHttpPipelineFilter>(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();API Endpoints
POST /mcp
- Purpose: Handle MCP JSON-RPC requests
- Content-Type: application/json
- Body: MCP JSON-RPC message
- Response: JSON-RPC response
GET /mcp/events
- Purpose: Server-Sent Events stream
- Accept: text/event-stream
- Response: SSE stream with MCP notifications
GET /mcp/capabilities
- Purpose: Server capability discovery
- Response: JSON object with server capabilities
Benefits
- Web Integration: Easy integration with web applications
- Real-time Updates: SSE support for live notifications
- Standard HTTP: Uses familiar HTTP protocols
- Backward Compatible: Original TCP transport unchanged
- RESTful: Standard HTTP methods and status codes
Transport Comparison
| Feature | TCP (Original) | HTTP |
|---|---|---|
| Protocol | Content-Length + JSON | HTTP + JSON |
| Port | 3000 (default) | 8080 (default) |
| Streaming | Bidirectional | SSE for notifications |
| Web Compatible | No | Yes |
| Firewall Friendly | No | Yes |
| Load Balancer Support | Limited | Full |
Both transports support the same MCP features and can be used simultaneously.
File: samples/LiveChat/ClientApp/README.md
LiveChat
This project was generated with Angular CLI version 6.0.0.
Development server
Run ng serve for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.
Code scaffolding
Run ng generate component component-name to generate a new component. You can also use ng generate directive|pipe|service|class|guard|interface|enum|module.
Build
Run ng build to build the project. The build artifacts will be stored in the dist/ directory. Use the --prod flag for a production build.
Running unit tests
Run ng test to execute the unit tests via Karma.
Running end-to-end tests
Run ng e2e to execute the end-to-end tests via Protractor.
Further help
To get more help on the Angular CLI use ng help or go check out the Angular CLI README.
File: samples/LiveChat/README.md
SuperSocket LiveChat Sample
A compl### WebSocket Protocol
The chat uses a simple text-based protocol:
- Connect:
CON- Join the chat room with a username - Message:
MSG <message>- Send a message to all users in the room
Example WebSocket Session
// 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!');Note: For development, only the HTTP WebSocket endpoint (ws://localhost:4040) is enabled to avoid SSL certificate issues. In production, you can enable the HTTPS WebSocket endpoint by adding the SSL listener configuration back to appsettings.json.application demonstrating how to build live chat functionality using SuperSocket WebSocket server with ASP.NET Core and Angular.
Features
- Real-time WebSocket Communication: Uses SuperSocket WebSocket server for bidirectional communication
- Command-based Architecture: Implements chat commands (CON for connect, MSG for message)
- Room Management: Supports user rooms with join/leave notifications
- Angular Frontend: Modern SPA with Material Design components
- HTTP WebSocket Support: WebSocket communication over HTTP (port 4040)
Getting Started
Prerequisites
- .NET 6.0 or later
- Node.js (for Angular development)
Running the Application
Build the Angular frontend:
bashcd ClientApp npm install npm run build cd ..Run the application:
bashdotnet runAccess the application:
- Web interface: http://localhost:5000 or https://localhost:5001
- WebSocket endpoint: ws://localhost:4040 (HTTP only for development)
WebSocket Protocol
The chat uses a simple text-based protocol:
- Connect:
CON- Join the chat room with a username - Message:
MSG <message>- Send a message to all users in the room
Example WebSocket Session
// Connect to WebSocket
const ws = new WebSocket('ws://localhost:4040');
// Join chat
ws.send('CON Alice');
// Send message
ws.send('MSG Hello everyone!');Architecture
- ChatSession: WebSocket session with user information
- RoomService: Manages users and message broadcasting
- Commands: CON and MSG command handlers for chat operations
- Angular Frontend: SPA with routing and Material UI components
Development
For development with Angular live reload:
- Start the .NET backend:
dotnet run - In another terminal, start Angular dev server:
cd ClientApp && npm start - Angular dev server will run on http://localhost:4200 with proxy to backend
Recent Updates
✅ Fixed SPA Services Issue: Removed deprecated Microsoft.AspNetCore.SpaServices.Extensions and modernized the approach to serve Angular static files directly.
The sample now works correctly with modern ASP.NET Core versions without deprecated SPA services.
File: samples/ConsoleEchoServer/README.md
Console Echo Server Sample
This sample demonstrates how to use SuperSocket with stdin/stdout for console-based communication.
Overview
The Console Echo Server shows how to:
- Use SuperSocket with console input/output streams
- Create a simple line-based protocol
- Handle text commands interactively
- Provide a command-line interface using SuperSocket's architecture
Features
- Console Integration: Reads from stdin and writes to stdout
- Interactive Commands: Supports various text commands
- Line-based Protocol: Uses
\r\nas message delimiter - Session Management: Proper session lifecycle handling
Available Commands
help- Show available commandstime- Display current server timeecho <message>- Echo back the provided messagequitorexit- Shutdown the server
Running the Sample
cd samples/ConsoleEchoServer
dotnet runUsage Example
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 <message> - 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...Implementation Details
Console Connection
- Uses
ConsoleConnectionwhich wrapsConsole.InandConsole.Outstreams - Provides bidirectional communication through standard streams
- Handles stream lifecycle properly without disposing system streams
Protocol
- Implements
LinePipelineFilterfor line-based text processing - Uses
\r\nas message terminator - Returns
StringPackageInfofor easy text handling
Session Handling
- Custom
ConsoleSessionclass extendsAppSession - Provides welcome message on connection
- Handles session cleanup on disconnection
Use Cases
This pattern is useful for:
- Command-line tools that need protocol processing
- Development and debugging tools
- Console-based administration interfaces
- Interactive testing utilities
- Pipe-based communication scenarios
Integration with Other Streams
The console connection can be adapted to work with other streams:
- File streams for batch processing
- Named pipes for inter-process communication
- Network streams for debugging
- Custom streams for specialized scenarios
File: src/SuperSocket.MCP/README.md
SuperSocket MCP (Model Context Protocol) Support
This package provides comprehensive support for the Model Context Protocol (MCP) in SuperSocket, enabling LLM applications to communicate with external tools and data sources through a standardized JSON-RPC 2.0 interface.
Features
- Complete MCP Protocol Support: Full JSON-RPC 2.0 implementation following MCP specification version 2024-11-05
- Multiple Transport Support: Stdio, HTTP (POST/SSE), and WebSocket transports
- Tool Integration: Easy registration and execution of MCP tools with JSON Schema validation
- Resource Management: Support for MCP resources with subscription capabilities
- Prompt Handling: MCP prompt management and templating
- Server-Sent Events: Real-time notifications via SSE for HTTP transport
- SuperSocket Integration: Leverages SuperSocket's robust pipeline architecture
- Extensibility: Clean interfaces for implementing custom handlers
- Error Handling: Proper MCP error responses with standard error codes
- Logging: Comprehensive logging integration
- Concurrent Operations: Thread-safe handler management
Transport Options
1. Stdio Transport (Recommended)
The stdio transport is the most common way to use MCP, especially for integration with AI assistants and command-line tools. It uses standard input/output for communication.
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<EchoToolHandler>()
.AddTool<MathToolHandler>();
})
.Build();
await host.RunAsync();2. WebSocket Transport
WebSocket transport allows web browsers and WebSocket clients to connect directly to MCP servers, enabling web-based integrations and real-time communication.
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;
using SuperSocket.WebSocket.Server;
var host = WebSocketHostBuilder.Create(args)
.ConfigureServices((hostCtx, services) =>
{
// Register MCP services
services.AddSingleton();
services.AddSingleton<McpServerInfo>(new McpServerInfo
{
Name = "SuperSocket MCP WebSocket Server",
Version = "1.0.0",
ProtocolVersion = "2024-11-05"
});
// Register sample tools
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
})
.UseMcp("mcp") // Use MCP with "mcp" sub-protocol
.ConfigureLogging((hostCtx, loggingBuilder) =>
{
loggingBuilder.AddConsole();
loggingBuilder.SetMinimumLevel(LogLevel.Information);
})
.Build();
await host.RunAsync();3. HTTP Transport
HTTP transport provides REST API endpoints and Server-Sent Events for web-compatible MCP communication.
using SuperSocket.MCP;
using SuperSocket.Server.Host;
var host = SuperSocketHostBuilder.Create<McpHttpRequest, McpHttpPipelineFilter>(args)
.UsePackageHandler(async (session, request) =>
{
var logger = session.Server.ServiceProvider.GetService(typeof(ILogger<McpHttpServer>)) as ILogger<McpHttpServer>;
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();using SuperSocket.MCP;
using SuperSocket.Server.Host;
var host = SuperSocketHostBuilder.Create<McpHttpRequest, McpHttpPipelineFilter>(args)
.UsePackageHandler(async (session, request) =>
{
var logger = session.Server.ServiceProvider.GetService(typeof(ILogger<McpHttpServer>)) as ILogger<McpHttpServer>;
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();Usage Examples
Stdio Transport
Run a stdio MCP server:
# Start the server
dotnet run --project samples/McpStdioServer/
# Connect with your MCP client
# The server reads from stdin and writes to stdoutWebSocket Transport
Connect to WebSocket MCP server from browser:
// 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);
};HTTP Transport API Endpoints
- POST /mcp: Send MCP JSON-RPC requests
- GET /mcp/events: Connect to Server-Sent Events for notifications
- GET /mcp/capabilities: Get server capabilities
Example HTTP usage:
# Send a tool call via HTTP POST
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "echo",
"arguments": {
"message": "Hello from HTTP!"
}
}
}'
# Connect to SSE for real-time notifications
curl -N -H "Accept: text/event-stream" http://localhost:8080/mcp/eventsTool Handler Implementation
Implement a Tool Handler
public class EchoToolHandler : IMcpToolHandler
{
public Task<McpTool> 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<McpToolResult> ExecuteAsync(Dictionary<string, object> arguments)
{
var message = arguments.TryGetValue("message", out var msg) ? msg.ToString() : "Hello!";
return Task.FromResult(new McpToolResult
{
Content = new List<McpContent>
{
new McpContent { Type = "text", Text = $"Echo: {message}" }
}
});
}
}3. Run the Server
For stdio transport:
dotnet run --project samples/McpStdioServer/McpStdioServer.csprojFor WebSocket transport:
dotnet run --project samples/McpWebSocketServer/McpWebSocketServer.csprojFor HTTP transport:
dotnet run --project samples/McpHttpServer/McpHttpServer.csprojThe servers will be ready to handle MCP connections via their respective transports.
Architecture
Core Components
- McpMessage: JSON-RPC 2.0 message structure
- McpPipelineFilter: Handles Content-Length header format parsing
- McpServer: Complete MCP protocol implementation
- Handler Interfaces: Clean abstractions for tools, resources, and prompts
- Extensions: Convenient methods for message sending and handling
Protocol Support
The implementation supports all major MCP protocol features:
- Initialization: Server/client handshake with capability negotiation
- Tools: Registration and execution of callable tools
- Resources: Management of readable resources
- Prompts: Template-based prompt handling
- Notifications: Asynchronous message delivery
- Error Handling: Standard JSON-RPC 2.0 error responses
Handler Interfaces
IMcpToolHandler
Implement this interface to create MCP tools:
public interface IMcpToolHandler
{
Task<McpTool> GetToolDefinitionAsync();
Task<McpToolResult> ExecuteAsync(Dictionary<string, object> arguments);
}IMcpResourceHandler
Implement this interface to create MCP resources:
public interface IMcpResourceHandler
{
Task<McpResource> GetResourceDefinitionAsync();
Task<McpResourceContent> ReadAsync(string uri);
}IMcpPromptHandler
Implement this interface to create MCP prompts:
public interface IMcpPromptHandler
{
Task<McpPrompt> GetPromptDefinitionAsync();
Task<McpPromptResult> GetPromptAsync(Dictionary<string, object>? arguments = null);
}Extensions for Different Transports
The package provides convenient extension methods for session handling:
Stdio Transport Extensions
// For stdio transport, use standard console I/O
// Messages are automatically handled through the console pipelineWebSocket Transport Extensions
// Send MCP messages over WebSocket
await session.SendMcpMessageAsync(message);
// WebSocket-specific helpers
await session.SendAsync(jsonMessage); // Send raw JSON stringHTTP Transport Extensions
// Send HTTP responses with MCP content
await session.SendHttpMcpResponseAsync(message);
await session.SendHttpMcpErrorAsync(id, code, message);
await session.SendHttpMcpResultAsync(id, result);
// Server-Sent Events support
var writer = await session.StartMcpServerSentEventsAsync();
await writer.SendMcpEventAsync(message);
await writer.SendMcpNotificationEventAsync(method, parameters);Testing
The package includes comprehensive tests covering:
- Message serialization/deserialization
- Tool handler execution
- Protocol compliance
- Error handling
Run tests with:
dotnet test test/SuperSocket.MCP.Tests/Examples
See the sample directories for complete examples:
- samples/McpStdioServer/: Stdio-based MCP server (recommended for most use cases)
- samples/McpWebSocketServer/: WebSocket-based MCP server with browser support
- samples/McpHttpServer/: HTTP-based MCP server with REST API and SSE support
All examples include:
- Echo tool: Simple message echoing
- Math tool: Basic arithmetic operations with error handling
- Complete server setup and configuration
Transport Comparison
| Feature | Stdio | WebSocket | HTTP (POST/SSE) |
|---|---|---|---|
| Protocol | JSON-RPC over stdio | JSON-RPC over WebSocket | HTTP + JSON-RPC |
| Use Case | CLI tools, AI assistants | Web apps, real-time apps | REST APIs, web services |
| Bidirectional | Yes | Yes | SSE for notifications |
| Web Compatible | No | Yes | Yes |
| Firewall Friendly | N/A | Yes | Yes |
| Load Balancer Support | N/A | Full | Full |
| Browser Support | No | Yes | Yes |
| Default Port | N/A | 8080 | 8080 |
| Best For | Command line integration | Interactive web apps | HTTP-based integrations |
All transports support the same MCP features and can be used based on your specific requirements.
Compatibility
- Compatible with MCP specification version 2024-11-05
- Requires .NET 6.0 or later
- Works with SuperSocket's existing infrastructure
- Supports stdio, WebSocket, and HTTP transports
- Stdio transport is the recommended approach for most MCP integrations
- WebSocket transport enables browser-based MCP clients
- HTTP transport uses standard HTTP methods with JSON-RPC 2.0 bodies
Error Handling
The implementation provides comprehensive error handling with standard JSON-RPC 2.0 error codes:
- Parse Error (-32700): Invalid JSON
- Invalid Request (-32600): Invalid request structure
- Method Not Found (-32601): Unknown method
- Invalid Params (-32602): Invalid parameters
- Internal Error (-32603): Internal server error
- Server Error (-32000): Application-specific errors
Contributing
When contributing to the MCP implementation:
- Follow the existing code patterns and style
- Add appropriate tests for new features
- Update documentation for API changes
- Ensure compatibility with the MCP specification
License
This package is part of SuperSocket and follows the same Apache 2.0 license.
File: src/SuperSocket.Http/README.md
SuperSocket HTTP Keep-Alive and Server-Sent Events
This enhancement adds comprehensive support for HTTP Keep-Alive connections and Server-Sent Events (SSE) to SuperSocket.Http.
Features
HTTP Keep-Alive Support
- Connection Reuse: Multiple HTTP requests over a single connection
- Automatic Lifecycle Management: Proper connection handling based on HTTP headers
- Configurable Timeouts: Customizable keep-alive timeout settings
- HTTP/1.1 Compliance: Full support for HTTP/1.1 keep-alive semantics
Server-Sent Events (SSE)
- Real-time Streaming: Push data to clients in real-time using
text/event-stream - Event Types: Support for custom event types and JSON events
- Event IDs: Automatic event ID generation and tracking for client reconnection
- Heartbeat Support: Automatic heartbeat to keep connections alive
- CORS Support: Built-in CORS headers for cross-origin requests
Quick Start
Basic HTTP Keep-Alive Server
using SuperSocket.Http;
var hostBuilder = Host.CreateDefaultBuilder()
.AsSuperSocketHostBuilder<HttpRequest, HttpKeepAliveFilter>()
.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();Server-Sent Events Stream
.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");
}
})API Reference
HttpResponse Class
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();HttpRequest Extensions
// Check for keep-alive
bool keepAlive = request.IsKeepAliveRequest();
// Check for SSE support
bool acceptsSSE = request.IsSSERequest();
// Get SSE last event ID for reconnection
string lastEventId = request.LastEventId;ServerSentEventWriter
var sseWriter = new ServerSentEventWriter(connection);
await sseWriter.SendInitialResponseAsync();
// Send different types of events
await sseWriter.SendEventAsync("Simple message");
await sseWriter.SendEventAsync("Custom event", "custom-type", "event-1");
await sseWriter.SendJsonEventAsync("{\"data\": \"json-payload\"}");
await sseWriter.SendHeartbeatAsync();Session Extensions
// 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 automaticallyConfiguration Options
HttpKeepAliveOptions
var keepAliveOptions = new HttpKeepAliveOptions
{
KeepAliveTimeoutSeconds = 60, // Connection timeout
MaxRequestsPerConnection = 1000, // Max requests per connection
EnableKeepAlive = true // Enable/disable keep-alive
};ServerSentEventsOptions
var sseOptions = new ServerSentEventsOptions
{
HeartbeatIntervalSeconds = 30, // Heartbeat interval
DefaultRetryIntervalMs = 3000, // Client retry interval
EnableCors = true, // Enable CORS headers
CorsOrigin = "*", // CORS origin
CorsAllowedHeaders = "Cache-Control" // CORS headers
};
var sseWriter = new ServerSentEventWriter(connection, sseOptions);Client-Side JavaScript
Basic SSE Client
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);
};Keep-Alive HTTP Requests
// Modern browsers automatically handle keep-alive for fetch requests
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data));
// Multiple requests will reuse the same connection
for (let i = 0; i < 5; i++) {
fetch(`/api/data/${i}`)
.then(response => response.json())
.then(data => console.log(`Request ${i}:`, data));
}Examples
See the /samples directory for complete examples:
- BasicHttpKeepAlive: Simple HTTP server with keep-alive support
- ServerSentEventsDemo: Real-time data streaming with SSE
- HttpApiServer: REST API server with keep-alive and JSON responses
Performance Considerations
Keep-Alive Benefits
- Reduced Connection Overhead: Fewer TCP handshakes
- Lower Latency: No connection establishment delay for subsequent requests
- Resource Efficiency: Fewer server sockets and client connections
SSE Considerations
- Memory Usage: Each SSE connection holds server resources
- Scaling: Consider connection limits and load balancing
- Heartbeat: Balance between responsiveness and resource usage
Compatibility
- HTTP/1.0: Basic support, keep-alive as extension
- HTTP/1.1: Full keep-alive support (default behavior)
- HTTP/2: Foundation for future HTTP/2 implementation
- Browsers: All modern browsers support SSE and keep-alive
Migration from Basic HTTP
- Replace
HttpPipelineFilterwithHttpKeepAliveFilter - Use
HttpResponseclass instead of manual response building - Leverage extension methods for cleaner code
- Add SSE endpoints as needed
// 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\"}");
})Troubleshooting
Common Issues
- Connection Not Reused: Check that client sends
Connection: keep-aliveheader - SSE Not Working: Verify
Accept: text/event-streamheader - CORS Issues: Configure SSE options with appropriate CORS settings
- Memory Leaks: Ensure proper disposal of SSE writers and heartbeat tasks
Debugging
Enable logging to see connection lifecycle:
.ConfigureLogging(logging =>
{
logging.AddConsole();
logging.SetMinimumLevel(LogLevel.Debug);
})Future Enhancements
- HTTP/2 Support: Binary framing and multiplexing
- WebSocket Upgrade: Seamless protocol switching
- Compression: Gzip/deflate support for responses
- Caching: Built-in HTTP caching headers support
File: README.CN.md
SuperSocket
SuperSocket 是一个用于 .NET 的高性能、可扩展的套接字服务器应用程序框架。它为构建自定义网络通信应用程序提供了强大的架构,支持包括 TCP、UDP 和 WebSocket 在内的多种协议。
- 项目主页: https://www.supersocket.net/
- 文档: https://docs.supersocket.net/
- License: https://www.apache.org/licenses/LICENSE-2.0
SuperSocket 的主要特点包括:
灵活的管道架构:
SuperSocket 实现了基于管道的处理模型,通过可自定义的过滤器高效处理传入数据。协议抽象:
该框架抽象了底层套接字操作,并为实现各种协议提供了简洁的接口。它内置支持 TCP、UDP、WebSocket 以及自定义协议。中间件支持:
可扩展的中间件系统,允许对连接和数据包进行自定义处理。会话管理:
SuperSocket 提供全面的会话处理功能,管理从建立到终止的连接生命周期。命令处理系统:
基于命令的处理模型,高效处理客户端请求。WebSocket 支持:
完整实现 WebSocket 协议,包括压缩等扩展功能。现代 .NET 集成:
SuperSocket 专为现代 .NET 构建,与 .NET 生态系统中的依赖注入、配置和日志记录功能无缝集成。跨平台:
作为 .NET 库,SuperSocket 可在 .NET 支持的所有平台上运行。客户端支持:
该框架包含用于建立与套接字服务器连接的客户端组件,包括代理功能。高性能:
SuperSocket 通过缓冲池和最小化内存分配,设计用于高吞吐量和低延迟场景,内存使用高效。
SuperSocket 适用于广泛的应用场景:
- 包括实时通信系统
- IoT 设备连接
- 游戏服务器
- 聊天应用程序
- 以及任何需要自定义网络协议的场景
Nuget Package
| Package | MyGet 测试版发布 | NuGet 稳定版发布 |
|---|---|---|
| SuperSocket.ProtoBase | ||
| SuperSocket.Primitives | ||
| SuperSocket.Connection | ||
| SuperSocket.Kestrel | ||
| SuperSocket.Server | ||
| SuperSocket.Server.Abstractions | ||
| SuperSocket.Command | ||
| SuperSocket.Client | ||
| SuperSocket.Client.Proxy | ||
| SuperSocket.WebSocket | ||
| SuperSocket.WebSocket.Server | ||
| SuperSocket.Udp | ||
| SuperSocket.SerialIO | ||
| SuperSocket.ProtoBuf | ||
| SuperSocket.MessagePack |
Nightly build packages: https://www.myget.org/F/supersocket/api/v3/index.json
SuperSocket 2.0 路线图:
- 2025:
- More documents
- Performance test/tuning
- Fix issues of the existing features
- Other features requested by users