Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 32 additions & 0 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions examples/McpToolAgent/McpToolAgent.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" />
<PackageReference Include="ModelContextProtocol" />
</ItemGroup>

<ItemGroup>
Expand Down
106 changes: 106 additions & 0 deletions examples/McpToolAgent/ParallelSearchExample.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Executes opt-in, anonymous Parallel MCP tools through SharpClaw's permission-aware executor.
/// </summary>
public static class ParallelSearchExample
{
/// <summary>The anonymous Streamable HTTP MCP endpoint.</summary>
public static readonly Uri Endpoint = new("https://search.parallel.ai/mcp");

/// <summary>Identifies this example on discovery and tool requests.</summary>
public const string UserAgent = "SharpClaw.Code-McpToolAgent/0.1.0";

/// <summary>
/// Discovers the supported tools, registers their schemas, and executes a single request.
/// No saved credentials or provider configuration are loaded.
/// </summary>
/// <param name="toolName">The local name: parallel_web_search or parallel_web_fetch.</param>
/// <param name="argumentsJson">Arguments matching the discovered remote tool schema.</param>
/// <param name="context">The caller's workspace, allowlist, and permission context.</param>
/// <param name="cancellationToken">Cancels discovery and execution.</param>
/// <param name="httpClient">Optional caller-owned HTTP client, primarily for transport testing.</param>
/// <returns>The permission decision and tool result, including remote errors.</returns>
public static async Task<ToolExecutionEnvelope> 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<string, string> { ["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<IPermissionPolicyEngine>());
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<ToolResult> ExecuteAsync(
ToolExecutionContext context,
ToolExecutionRequest request,
CancellationToken cancellationToken)
{
var arguments = JsonSerializer.Deserialize<Dictionary<string, object?>>(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<TextContentBlock>().Select(block => block.Text));
if (result.IsError == true)
{
return CreateFailureResult(context, request, output);
}

return CreateSuccessResult(context, request, output, result);
}
}
}
47 changes: 47 additions & 0 deletions examples/McpToolAgent/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <query> | --parallel-search fetch <url>");
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);

Expand Down
127 changes: 127 additions & 0 deletions tests/SharpClaw.Code.UnitTests/Mcp/ParallelSearchExampleTests.cs
Original file line number Diff line number Diff line change
@@ -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, 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<ObservedRequest> Requests { get; } = [];
public bool ToolError { get; init; }

protected override async Task<HttpResponseMessage> 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")
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\examples\McpToolAgent\McpToolAgent.csproj" />
<ProjectReference Include="..\..\src\SharpClaw.Code.Agents\SharpClaw.Code.Agents.csproj" />
<ProjectReference Include="..\..\src\SharpClaw.Code.Acp\SharpClaw.Code.Acp.csproj" />
<ProjectReference Include="..\..\src\SharpClaw.Code.Commands\SharpClaw.Code.Commands.csproj" />
Expand Down
Loading