Skip to content

MCP Client — Connect to External MCP Servers

Granit.Mcp.Client provides a named factory for connecting to external MCP servers — ERP systems, data APIs, CLI tools, or any MCP-compatible service.

Terminal window
dotnet add package Granit.Mcp.Client
builder.AddGranitMcpClient();

Named connections are configured in appsettings.json:

{
"Mcp": {
"Client": {
"Connections": {
"erp": {
"Url": "https://erp.internal/mcp",
"Transport": "http"
},
"data-tools": {
"Transport": "stdio",
"Command": "dotnet",
"Arguments": ["run", "--project", "../DataTools/DataTools.csproj"]
},
"python-analyzer": {
"Transport": "stdio",
"Command": "python",
"Arguments": ["-m", "analyzer_mcp"]
}
}
}
}
}
PropertyTypeDefaultRequiredDescription
Urlstring?HTTPServer URL (must use HTTPS in production)
Transportstring"http""http" or "stdio"
AllowInsecureTransportboolfalseAllow http:// (non-TLS) transport. Enable only for local development
Commandstring?stdioExecutable command
Argumentsstring[][]Command-line arguments
public sealed class ExportService(IMcpClientFactory mcpFactory)
{
public async Task<IReadOnlyList<McpClientTool>> GetErpToolsAsync(CancellationToken ct)
{
await using McpClient client = await mcpFactory.CreateAsync("erp", ct);
return await client.ListToolsAsync(cancellationToken: ct);
}
public async Task<CallToolResult> InvokeErpToolAsync(
string toolName, Dictionary<string, object?> args, CancellationToken ct)
{
await using McpClient client = await mcpFactory.CreateAsync("erp", ct);
return await client.CallToolAsync(toolName, args, cancellationToken: ct);
}
}

For remote MCP servers accessible via HTTPS. The SDK uses Streamable HTTP (with automatic fallback to SSE for older servers):

{
"erp": {
"Url": "https://erp.internal/mcp"
}
}

For local tools running as child processes. The factory spawns the process and communicates via stdin/stdout:

{
"local-tools": {
"Transport": "stdio",
"Command": "dotnet",
"Arguments": ["run", "--project", "../InvoiceTools/"]
}
}

The factory throws InvalidOperationException for configuration errors:

ScenarioException message
Connection not found"MCP connection 'xyz' is not configured"
Unsupported transport"Unsupported MCP transport type 'websocket'"
Missing URL (HTTP)ArgumentException from ThrowIfNullOrWhiteSpace
Missing command (stdio)ArgumentException from ThrowIfNullOrWhiteSpace