From a49beabafcd08edf5898c139666bf8dcf6e4ff12 Mon Sep 17 00:00:00 2001 From: George at Parallel Date: Wed, 7 Oct 2026 00:26:22 +0000 Subject: [PATCH 1/2] Add opt-in Parallel Search MCP tool example --- README.md | 4 + docs/mcp.md | 32 +++++ examples/McpToolAgent/McpToolAgent.csproj | 1 + .../McpToolAgent/ParallelSearchExample.cs | 106 +++++++++++++++ examples/McpToolAgent/Program.cs | 47 +++++++ .../Mcp/ParallelSearchExampleTests.cs | 127 ++++++++++++++++++ .../SharpClaw.Code.UnitTests.csproj | 1 + 7 files changed, 318 insertions(+) create mode 100644 examples/McpToolAgent/ParallelSearchExample.cs create mode 100644 tests/SharpClaw.Code.UnitTests/Mcp/ParallelSearchExampleTests.cs diff --git a/README.md b/README.md index cca871e..1df4a3b 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,10 @@ The solution includes embeddable host samples under `examples/`: - `WorkerServiceHost` for lifecycle-managed background hosting - `McpToolAgent` for MCP-aware host composition +`McpToolAgent` also offers a [runnable Parallel Search MCP example](docs/mcp.md#runnable-parallel-search-example) +for anonymous web search and page extraction through the SharpClaw tool registry +and permission executor, without a model provider key. + ## Testing ```bash diff --git a/docs/mcp.md b/docs/mcp.md index 0e406e4..d40a991 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -55,3 +55,35 @@ JSON **`DataJson`** for register/start/stop/restart uses **`ProtocolJsonContext` ## Diagnostics Runtime **doctor** includes **`McpRegistryHealthCheck`** (registry + optional host). + +## Runnable Parallel Search example + +`examples/McpToolAgent` includes an opt-in command for searching and fetching public +web content with [Parallel Search MCP](https://docs.parallel.ai/integrations/mcp/search-mcp). +It connects to `https://search.parallel.ai/mcp` using the official SDK's +Streamable HTTP transport. The anonymous endpoint needs no Parallel API key and +is free for exploration and light use, subject to rate limits. + +From the repository root, with the .NET 10 SDK installed: + +```shell +dotnet restore examples/McpToolAgent/McpToolAgent.csproj +dotnet build examples/McpToolAgent/McpToolAgent.csproj --configuration Release +dotnet run --project examples/McpToolAgent --configuration Release --no-build -- --parallel-search search "C# CancellationToken documentation" +dotnet run --project examples/McpToolAgent --configuration Release --no-build -- --parallel-search fetch https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads +``` + +Each command discovers the remote tool schema, registers it as +`parallel_web_search` or `parallel_web_fetch` in a SharpClaw `ToolRegistry`, and +dispatches it through `ToolExecutor` with a read-only permission context and an +explicit tool allowlist. Search prints source URLs and excerpts; fetch prints +extracted page content. Remote tool errors produce a failing exit code. +The example identifies its requests with the User-Agent +`SharpClaw.Code-McpToolAgent/0.1.0`, passes cancellation through discovery and +execution, and bounds each command to 60 seconds. Ctrl+C cancels the request. + +These commands execute tools directly, without a model or an agent reasoning +loop. They do not load the sample's model-provider configuration or saved +credentials. Running `McpToolAgent` without `--parallel-search` still runs the +original provider-backed echo example. The built-in `web_search` and `web_fetch` +tools and workspace MCP registrations are unaffected. diff --git a/examples/McpToolAgent/McpToolAgent.csproj b/examples/McpToolAgent/McpToolAgent.csproj index bbc30f8..a5d1ca5 100644 --- a/examples/McpToolAgent/McpToolAgent.csproj +++ b/examples/McpToolAgent/McpToolAgent.csproj @@ -7,6 +7,7 @@ + diff --git a/examples/McpToolAgent/ParallelSearchExample.cs b/examples/McpToolAgent/ParallelSearchExample.cs new file mode 100644 index 0000000..985a2d2 --- /dev/null +++ b/examples/McpToolAgent/ParallelSearchExample.cs @@ -0,0 +1,106 @@ +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using ModelContextProtocol.Client; +using ModelContextProtocol.Protocol; +using SharpClaw.Code.Infrastructure; +using SharpClaw.Code.Permissions; +using SharpClaw.Code.Permissions.Abstractions; +using SharpClaw.Code.Protocol.Enums; +using SharpClaw.Code.Protocol.Models; +using SharpClaw.Code.Tools.BuiltIn; +using SharpClaw.Code.Tools.Execution; +using SharpClaw.Code.Tools.Models; +using SharpClaw.Code.Tools.Registry; + +namespace McpToolAgent; + +/// +/// Executes opt-in, anonymous Parallel MCP tools through SharpClaw's permission-aware executor. +/// +public static class ParallelSearchExample +{ + /// The anonymous Streamable HTTP MCP endpoint. + public static readonly Uri Endpoint = new("https://search.parallel.ai/mcp"); + + /// Identifies this example on discovery and tool requests. + public const string UserAgent = "SharpClaw.Code-McpToolAgent/0.1.0"; + + /// + /// Discovers the supported tools, registers their schemas, and executes a single request. + /// No saved credentials or provider configuration are loaded. + /// + /// The local name: parallel_web_search or parallel_web_fetch. + /// Arguments matching the discovered remote tool schema. + /// The caller's workspace, allowlist, and permission context. + /// Cancels discovery and execution. + /// Optional caller-owned HTTP client, primarily for transport testing. + /// The permission decision and tool result, including remote errors. + public static async Task ExecuteAsync( + string toolName, + string argumentsJson, + ToolExecutionContext context, + CancellationToken cancellationToken, + HttpClient? httpClient = null) + { + if (toolName is not ("parallel_web_search" or "parallel_web_fetch")) + { + throw new ArgumentException("Choose parallel_web_search or parallel_web_fetch.", nameof(toolName)); + } + + var options = new HttpClientTransportOptions + { + Endpoint = Endpoint, + TransportMode = HttpTransportMode.StreamableHttp, + ConnectionTimeout = TimeSpan.FromSeconds(30), + AdditionalHeaders = new Dictionary { ["User-Agent"] = UserAgent } + }; + var transport = httpClient is null + ? new HttpClientTransport(options) + : new HttpClientTransport(options, httpClient, ownsHttpClient: false); + await using var client = await McpClient.CreateAsync(transport, cancellationToken: cancellationToken); + var discovered = await client.ListToolsAsync(cancellationToken: cancellationToken); + var remoteName = toolName["parallel_".Length..]; + var remoteTool = discovered.Single(tool => tool.Name == remoteName); + var registry = new ToolRegistry([new ParallelMcpTool(client, remoteTool)]); + + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSharpClawInfrastructure(); + services.AddSharpClawPermissions(); + using var provider = services.BuildServiceProvider(); + var executor = new ToolExecutor(registry, provider.GetRequiredService()); + return await executor.ExecuteAsync(toolName, argumentsJson, context, cancellationToken); + } + + private sealed class ParallelMcpTool(McpClient client, McpClientTool remoteTool) : SharpClawToolBase + { + public override ToolDefinition Definition { get; } = new( + "parallel_" + remoteTool.Name, + remoteTool.Description ?? "Search or fetch public web content through Parallel MCP.", + ApprovalScope.ToolExecution, + IsDestructive: false, + RequiresApproval: false, + InputTypeName: "ParallelMcpArguments", + InputDescription: "Arguments follow the discovered MCP input schema.", + Tags: ["web", "network", "parallel", "mcp"], + InputSchemaJson: remoteTool.JsonSchema.GetRawText()); + + public override async Task ExecuteAsync( + ToolExecutionContext context, + ToolExecutionRequest request, + CancellationToken cancellationToken) + { + var arguments = JsonSerializer.Deserialize>(request.ArgumentsJson) + ?? throw new ArgumentException("Tool arguments must be a JSON object."); + var result = await client.CallToolAsync(remoteTool.Name, arguments, cancellationToken: cancellationToken); + var output = string.Join(Environment.NewLine, + result.Content.OfType().Select(block => block.Text)); + if (result.IsError == true) + { + return CreateFailureResult(context, request, output); + } + + return CreateSuccessResult(context, request, output, result); + } + } +} diff --git a/examples/McpToolAgent/Program.cs b/examples/McpToolAgent/Program.cs index 38d9e7a..27b8376 100644 --- a/examples/McpToolAgent/Program.cs +++ b/examples/McpToolAgent/Program.cs @@ -7,6 +7,53 @@ using SharpClaw.Code.Runtime.Composition; using SharpClaw.Code.Tools.Abstractions; +if (args.Length > 0 && args[0] == "--parallel-search") +{ + if (args.Length != 3 || args[1] is not ("search" or "fetch")) + { + Console.Error.WriteLine("Usage: --parallel-search search | --parallel-search fetch "); + Environment.ExitCode = 2; + return; + } + + using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(60)); + Console.CancelKeyPress += (_, eventArgs) => + { + eventArgs.Cancel = true; + cancellation.Cancel(); + }; + + var conversationId = Guid.NewGuid().ToString("N"); + var toolName = args[1] == "search" ? "parallel_web_search" : "parallel_web_fetch"; + var arguments = args[1] == "search" + ? System.Text.Json.JsonSerializer.Serialize(new + { + objective = args[2], search_queries = new[] { args[2] }, session_id = conversationId + }) + : System.Text.Json.JsonSerializer.Serialize(new + { + urls = new[] { args[2] }, session_id = conversationId + }); + var workspace = Directory.GetCurrentDirectory(); + var context = new SharpClaw.Code.Tools.Models.ToolExecutionContext( + conversationId, "parallel-example", workspace, workspace, + PermissionMode.ReadOnly, OutputFormat.Text, null, + AllowedTools: ["parallel_web_search", "parallel_web_fetch"], IsInteractive: false); + + try + { + var envelope = await ParallelSearchExample.ExecuteAsync(toolName, arguments, context, cancellation.Token); + Console.WriteLine(envelope.Result.Output ?? envelope.Result.ErrorMessage); + Environment.ExitCode = envelope.Result.Succeeded ? 0 : 1; + } + catch (Exception exception) when (exception is not OutOfMemoryException) + { + Console.Error.WriteLine(exception.Message); + Environment.ExitCode = 1; + } + return; +} + var builder = Host.CreateApplicationBuilder(args); builder.Services.AddSharpClawRuntime(builder.Configuration); diff --git a/tests/SharpClaw.Code.UnitTests/Mcp/ParallelSearchExampleTests.cs b/tests/SharpClaw.Code.UnitTests/Mcp/ParallelSearchExampleTests.cs new file mode 100644 index 0000000..8db1e22 --- /dev/null +++ b/tests/SharpClaw.Code.UnitTests/Mcp/ParallelSearchExampleTests.cs @@ -0,0 +1,127 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using McpToolAgent; +using SharpClaw.Code.Protocol.Enums; +using SharpClaw.Code.Tools.Models; + +namespace SharpClaw.Code.UnitTests.Mcp; + +public sealed class ParallelSearchExampleTests +{ + [Theory] + [InlineData("web_search", "{\"objective\":\"C# cancellation\",\"search_queries\":[\"C# cancellation tokens\"]}")] + [InlineData("web_fetch", "{\"urls\":[\"https://learn.microsoft.com/dotnet/\"]}")] + public async Task ExecutesDiscoveredToolThroughRegistryWithAnonymousProjectHeaders(string tool, string arguments) + { + using var handler = new McpHandler(); + using var httpClient = new HttpClient(handler); + var result = await ParallelSearchExample.ExecuteAsync( + "parallel_" + tool, arguments, Context(), CancellationToken.None, httpClient); + + Assert.True(result.PermissionDecision.IsAllowed); + Assert.True(result.Result.Succeeded); + Assert.Contains("https://learn.microsoft.com/dotnet/", result.Result.Output); + Assert.NotNull(result.Result.StructuredOutputJson); + Assert.Contains(handler.Requests, request => request.Method == "initialize"); + Assert.Contains(handler.Requests, request => request.Method == "tools/list"); + var call = Assert.Single(handler.Requests.Where(request => request.Method == "tools/call")); + using var payload = JsonDocument.Parse(call.Body); + Assert.Equal(tool, payload.RootElement.GetProperty("params").GetProperty("name").GetString()); + Assert.Equal(JsonSerializer.Serialize(JsonDocument.Parse(arguments).RootElement), + JsonSerializer.Serialize(payload.RootElement.GetProperty("params").GetProperty("arguments"))); + Assert.All(handler.Requests, request => + { + Assert.Equal(ParallelSearchExample.Endpoint, request.Url); + Assert.Equal(ParallelSearchExample.UserAgent, request.UserAgent); + Assert.Null(request.Authorization); + }); + } + + [Fact] + public async Task DeniedAllowlistPreventsRemoteToolCall() + { + using var handler = new McpHandler(); + using var httpClient = new HttpClient(handler); + var result = await ParallelSearchExample.ExecuteAsync( + "parallel_web_search", "{}", Context() with { AllowedTools = ["echo"] }, CancellationToken.None, httpClient); + + Assert.False(result.PermissionDecision.IsAllowed); + Assert.False(result.Result.Succeeded); + Assert.DoesNotContain(handler.Requests, request => request.Method == "tools/call"); + } + + [Fact] + public async Task RemoteToolErrorRemainsFailure() + { + using var handler = new McpHandler { ToolError = true }; + using var httpClient = new HttpClient(handler); + var result = await ParallelSearchExample.ExecuteAsync( + "parallel_web_fetch", "{}", Context(), CancellationToken.None, httpClient); + + Assert.False(result.Result.Succeeded); + Assert.Equal("fixture error", result.Result.ErrorMessage); + } + + private static ToolExecutionContext Context() + { + var workspace = Path.GetTempPath(); + return new("parallel-test", "test-turn", workspace, workspace, + PermissionMode.ReadOnly, OutputFormat.Text, null, + AllowedTools: ["parallel_web_search", "parallel_web_fetch"], IsInteractive: false); + } + + private sealed record ObservedRequest(Uri? Url, string UserAgent, string? Authorization, string Method, string Body); + + private sealed class McpHandler : HttpMessageHandler + { + public List Requests { get; } = []; + public bool ToolError { get; init; } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.Method != HttpMethod.Post) + { + return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed); + } + + var body = await request.Content!.ReadAsStringAsync(cancellationToken); + using var document = JsonDocument.Parse(body); + var root = document.RootElement; + var method = root.GetProperty("method").GetString()!; + Requests.Add(new(request.RequestUri, request.Headers.UserAgent.ToString(), + request.Headers.Authorization?.ToString(), method, body)); + if (!root.TryGetProperty("id", out var id)) + { + return new HttpResponseMessage(HttpStatusCode.Accepted); + } + + object result = method switch + { + "initialize" => new + { + protocolVersion = root.GetProperty("params").GetProperty("protocolVersion").GetString(), + capabilities = new { tools = new { } }, + serverInfo = new { name = "parallel-fixture", version = "1.0.0" } + }, + "tools/list" => new + { + tools = new[] { "web_search", "web_fetch" }.Select(name => new + { + name, description = "Fixture tool", inputSchema = new { type = "object" } + }) + }, + "tools/call" => new + { + content = new[] { new { type = "text", text = ToolError ? "fixture error" : "C# documentation https://learn.microsoft.com/dotnet/" } }, + isError = ToolError + }, + _ => throw new InvalidOperationException("Unexpected MCP method: " + method) + }; + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(JsonSerializer.Serialize(new { jsonrpc = "2.0", id, result }), Encoding.UTF8, "application/json") + }; + } + } +} diff --git a/tests/SharpClaw.Code.UnitTests/SharpClaw.Code.UnitTests.csproj b/tests/SharpClaw.Code.UnitTests/SharpClaw.Code.UnitTests.csproj index 617b3d7..4f1c3d3 100644 --- a/tests/SharpClaw.Code.UnitTests/SharpClaw.Code.UnitTests.csproj +++ b/tests/SharpClaw.Code.UnitTests/SharpClaw.Code.UnitTests.csproj @@ -20,6 +20,7 @@ + From 15a8162debdb2c45490f64efc095707f35cbfd50 Mon Sep 17 00:00:00 2001 From: George at Parallel Date: Wed, 7 Oct 2026 00:28:35 +0000 Subject: [PATCH 2/2] Use xUnit predicate assertion without analyzer warnings --- .../SharpClaw.Code.UnitTests/Mcp/ParallelSearchExampleTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/SharpClaw.Code.UnitTests/Mcp/ParallelSearchExampleTests.cs b/tests/SharpClaw.Code.UnitTests/Mcp/ParallelSearchExampleTests.cs index 8db1e22..dd4c72b 100644 --- a/tests/SharpClaw.Code.UnitTests/Mcp/ParallelSearchExampleTests.cs +++ b/tests/SharpClaw.Code.UnitTests/Mcp/ParallelSearchExampleTests.cs @@ -25,7 +25,7 @@ public async Task ExecutesDiscoveredToolThroughRegistryWithAnonymousProjectHeade Assert.NotNull(result.Result.StructuredOutputJson); Assert.Contains(handler.Requests, request => request.Method == "initialize"); Assert.Contains(handler.Requests, request => request.Method == "tools/list"); - var call = Assert.Single(handler.Requests.Where(request => request.Method == "tools/call")); + var call = Assert.Single(handler.Requests, request => request.Method == "tools/call"); using var payload = JsonDocument.Parse(call.Body); Assert.Equal(tool, payload.RootElement.GetProperty("params").GetProperty("name").GetString()); Assert.Equal(JsonSerializer.Serialize(JsonDocument.Parse(arguments).RootElement),