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 docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,10 @@ Agents:

The agent then sees all tools from the Puppeteer server alongside the built-in FileSystem and Shell tools.

Tool names have to be unique, or the provider rejects the request. When a server's tool has the same name as a
built-in tool or another server's tool, it's offered as `<server>_<tool>` instead, such as `Sql_query_database`.
Built-in tools always keep their names. This applies in `fuseraft repl` too.

---

## Servers provided by the launcher
Expand Down
10 changes: 8 additions & 2 deletions src/Cli/Commands/Repl/ReplSessionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -378,9 +378,15 @@ public void ResetPlanState()
RecoveryHint = null;
}

public List<AIFunction> GetActiveTools() => [.. ToolsByCategory
public List<AIFunction> GetActiveTools() => McpToolNames.Disambiguate([.. ToolsByCategory
.Where(kv => !DisabledCategories.Contains(kv.Key))
.SelectMany(kv => kv.Value.Where(f => IsToolAllowed(f.Name) && PassesSafeMode(kv.Key, f)))];
.SelectMany(kv => kv.Value
.Where(f => IsToolAllowed(f.Name) && PassesSafeMode(kv.Key, f))
.Select(f => (McpServerOf(kv.Key), f)))]);

// An MCP server's tools sit under "mcp:<server>"; every other category is built in.
private static string? McpServerOf(string category) =>
category.StartsWith("mcp:", StringComparison.OrdinalIgnoreCase) ? category["mcp:".Length..] : null;

/// <summary>
/// Safe mode's check for an MCP server's tools, which no capability map names: like Http, a server can reach
Expand Down
3 changes: 2 additions & 1 deletion src/Cli/Commands/Repl/ReplTurn.cs
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,8 @@ private static async Task RunLoopAsync(ReplSessionContext ctx, CancellationToken
if (!ctx.JsonMode && ReplInput.Screen is null)
AnsiConsole.Markup((modeTags.Count > 0 ? $"[dim][[{string.Join("·", modeTags)}]] {turnLabel}[/]" : $"[dim]{turnLabel}[/]") + "[bold cyan]>[/] ");

ReplAutoTitle.MaybeStart(ctx);
// Runs alongside the next prompt: a title isn't worth making anyone wait.
_ = ReplAutoTitle.MaybeStart(ctx);
if (ctx.TitleUnsaved) await SaveSnapshotAsync(ctx);

// Sent while the REPL was busy with something no turn read from (a command, plan steps): it starts the next turn.
Expand Down
20 changes: 13 additions & 7 deletions src/Infrastructure/Agents/AgentToolResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.Extensions.AI;
using fuseraft.Core;
using fuseraft.Core.Models;
using fuseraft.Infrastructure.Mcp;
using fuseraft.Infrastructure.Plugins;

namespace fuseraft.Infrastructure.Agents;
Expand Down Expand Up @@ -34,11 +35,13 @@ public List<AIFunction> ConvertPluginTools(
HashSet<ITurnResettable> turnResettables,
object resettablesLock)
{
var tools = new List<AIFunction>();
// Each tool with the MCP server it came from (null for built-in ones), so clashing names can be told apart.
var tools = new List<(string? Server, AIFunction Tool)>();

foreach (var pluginName in config.Plugins)
{
IEnumerable<AIFunction> functions;
string? server = null;

// "Skills" is handled by AgentSkillsProvider (UseAIContextProviders), which
// injects load_skill / run_skill_script as tools on the chat client pipeline.
Expand Down Expand Up @@ -92,6 +95,7 @@ public List<AIFunction> ConvertPluginTools(
else if (pluginRegistry.TryGetAIFunctions(pluginName, out var aiFunctions))
{
functions = aiFunctions;
server = pluginName;
}
else if (pluginRegistry.TryGetAll(pluginName, out var plugins))
{
Expand All @@ -115,7 +119,7 @@ public List<AIFunction> ConvertPluginTools(
if (config.Capabilities.TryGetValue(pluginName, out var caps) && caps.Count > 0)
functions = functions.Where(f => PluginCapabilityMap.IsAllowed(f.Name, caps));

tools.AddRange(functions);
tools.AddRange(functions.Select(f => (server, f)));
}

// Collect any newly-seen ITurnResettable plugin instances so OnAgentTurnStarting
Expand All @@ -126,7 +130,7 @@ public List<AIFunction> ConvertPluginTools(
lock (resettablesLock) turnResettables.Add(tr);
}

return tools;
return McpToolNames.Disambiguate(tools);
}

/// <summary>
Expand Down Expand Up @@ -174,7 +178,7 @@ public static List<AIFunction> WrapWithNotifications(
// Assembles the tool list for a subagent spawned by SubagentPlugin.
// When config.SubagentPlugins is set, uses those plugins (capability-filtered like normal agents).
// Otherwise falls back to the expanded default: FileSystem read, Search, Shell run, Git read.
private static List<AIFunction> BuildSubagentTools(
internal static List<AIFunction> BuildSubagentTools(
AgentConfig config,
PluginRegistry pluginRegistry,
SecurityConfig? securityConfig)
Expand All @@ -184,11 +188,13 @@ private static List<AIFunction> BuildSubagentTools(
if (config.SubagentPlugins is { Count: > 0 })
{
// Custom plugin list — resolve and capability-filter the same way BuildTools does.
var custom = new List<(string? Server, AIFunction Tool)>();
foreach (var name in config.SubagentPlugins)
{
IEnumerable<AIFunction> fns;
string? server = null;
if (pluginRegistry.TryGetAIFunctions(name, out var aiFns))
fns = aiFns;
(fns, server) = (aiFns, name);
else if (pluginRegistry.TryGetAll(name, out var ps))
fns = ps.SelectMany(PluginRegistry.GetFunctionsFromObject);
else
Expand All @@ -199,9 +205,9 @@ private static List<AIFunction> BuildSubagentTools(
if (config.Capabilities.TryGetValue(name, out var caps) && caps.Count > 0)
fns = fns.Where(f => PluginCapabilityMap.IsAllowed(f.Name, caps));

tools.AddRange(fns);
custom.AddRange(fns.Select(f => (server, f)));
}
return tools;
return McpToolNames.Disambiguate(custom);
}

// Default: expanded read-oriented set. FileSystem (sandboxed, read ops only).
Expand Down
65 changes: 65 additions & 0 deletions src/Infrastructure/Mcp/McpToolNames.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System.Text.RegularExpressions;
using Microsoft.Extensions.AI;

namespace fuseraft.Infrastructure.Mcp;

/// <summary>
/// Keeps tool names unique when MCP servers bring tools named like another server's or a built-in tool: providers
/// reject a request whose tools share a name, which would fail every turn.
/// </summary>
public static partial class McpToolNames
{
/// <summary>The longest tool name providers accept (Anthropic and OpenAI both allow 64).</summary>
public const int MaxLength = 64;

/// <summary>
/// The tools as the model should see them. A built-in tool (<c>Server</c> null) keeps its name; an MCP tool
/// whose name another tool also has is offered as <c>&lt;server&gt;_&lt;name&gt;</c>, and still calls its own.
/// </summary>
public static List<AIFunction> Disambiguate(IReadOnlyList<(string? Server, AIFunction Tool)> tools)
{
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var (_, tool) in tools)
counts[tool.Name] = counts.GetValueOrDefault(tool.Name) + 1;
if (counts.Values.All(c => c == 1))
return [.. tools.Select(t => t.Tool)];

bool Clashes((string? Server, AIFunction Tool) t) => t.Server is not null && counts[t.Tool.Name] > 1;

var taken = tools.Where(t => !Clashes(t)).Select(t => t.Tool.Name).ToHashSet(StringComparer.Ordinal);
var result = new List<AIFunction>(tools.Count);
foreach (var t in tools)
{
if (!Clashes(t))
{
result.Add(t.Tool);
continue;
}
var name = Unique($"{Unsafe().Replace(t.Server!, "_")}_{t.Tool.Name}", taken);
taken.Add(name);
result.Add(new RenamedFunction(t.Tool, name));
}
return result;
}

private static string Unique(string name, HashSet<string> taken)
{
var candidate = Fit(name, "");
for (var n = 2; taken.Contains(candidate); n++)
candidate = Fit(name, $"_{n}");
return candidate;
}

private static string Fit(string name, string suffix) =>
(name.Length + suffix.Length <= MaxLength ? name : name[..(MaxLength - suffix.Length)]) + suffix;

// Server names come from config and may hold characters tool names can't.
[GeneratedRegex("[^A-Za-z0-9_-]")]
private static partial Regex Unsafe();

// Only the name changes: calls, schema and GetService (approval gates, read-only hints) go to the tool itself.
private sealed class RenamedFunction(AIFunction inner, string name) : DelegatingAIFunction(inner)
{
public override string Name => name;
}
}
55 changes: 55 additions & 0 deletions tests/FuseraftCli.Tests/AgentToolResolverTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using fuseraft.Infrastructure;
using fuseraft.Infrastructure.Agents;
using fuseraft.Infrastructure.Plugins;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging.Abstractions;

namespace FuseraftCli.Tests;
Expand Down Expand Up @@ -44,6 +45,60 @@ public void DelegateToolName_MatchesTheNameReflectionGivesDelegateAsync()
Assert.Contains(SubagentPlugin.DelegateToolName, names);
}

[Fact]
public void McpServersWithClashingTools_GetUniqueNames_AndBuiltInsKeepTheirs()
{
// Two MCP servers (registered as AI functions) sharing query_database, one also shadowing a built-in.
_registry.RegisterAIFunctions("Sql", [Fake("query_database"), Fake("read_file")]);
_registry.RegisterAIFunctions("Local", [Fake("query_database"), Fake("list_tables")]);

var names = Resolve(Agent("FileSystem", "Sql", "Local")).Select(t => t.Name).ToList();

Assert.Equal(names.Count, names.Distinct(StringComparer.Ordinal).Count());
Assert.Contains("read_file", names);
Assert.Contains("Sql_read_file", names);
Assert.Contains("Sql_query_database", names);
Assert.Contains("Local_query_database", names);
Assert.Contains("list_tables", names);
Assert.DoesNotContain("query_database", names);
}

[Fact]
public void SubagentPlugins_WithClashingMcpTools_GetUniqueNames()
{
_registry.RegisterAIFunctions("Sql", [Fake("query_database")]);
_registry.RegisterAIFunctions("Local", [Fake("query_database")]);

var tools = AgentToolResolver.BuildSubagentTools(Agent(["Sql", "Local"], "Subagent"), _registry, null);

Assert.Equal(["Sql_query_database", "Local_query_database"], tools.Select(t => t.Name));
}

private static AIFunction Fake(string name) => AIFunctionFactory.Create(() => name, name, $"Fake {name}.");

private static AgentConfig Agent(params string[] plugins) => Agent(null, plugins);

private static AgentConfig Agent(List<string>? subagentPlugins, params string[] plugins) => new()
{
Name = "TestAgent",
Instructions = "You are a test agent.",
Plugins = [.. plugins],
SubagentPlugins = subagentPlugins,
Model = new ModelConfig
{
ModelId = "grok-4-1-fast-reasoning",
Endpoint = "https://api.x.ai/v1",
ApiKeyEnvVar = FakeApiKeyVar,
},
};

private List<AIFunction> Resolve(AgentConfig config)
{
var factory = new ChatClientFactory();
var resolver = new AgentToolResolver(factory, _registry, null, null, null, null);
return resolver.ConvertPluginTools(config, factory.Resolve(config.Model), null, [], new object());
}

private List<string> ResolveToolNames(params string[] plugins)
{
var config = new AgentConfig
Expand Down
2 changes: 1 addition & 1 deletion tests/FuseraftCli.Tests/McpSessionManagerStderrTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace FuseraftCli.Tests;
/// </summary>
public sealed class McpSessionManagerStderrTests
{
private static McpServerConfig Server(string script, Dictionary<string, string>? env = null) => OperatingSystem.IsWindows()
private static McpServerConfig Server(string script, Dictionary<string, string?>? env = null) => OperatingSystem.IsWindows()
? new() { Name = "noisy", Command = "cmd.exe", Args = ["/c", script], Env = env ?? [] }
: new() { Name = "noisy", Command = "sh", Args = ["-c", script], Env = env ?? [] };

Expand Down
89 changes: 89 additions & 0 deletions tests/FuseraftCli.Tests/McpToolNamesTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using Microsoft.Extensions.AI;
using fuseraft.Infrastructure.Mcp;

namespace FuseraftCli.Tests;

public sealed class McpToolNamesTests
{
private static AIFunction Fake(string name, string result = "ok") =>
AIFunctionFactory.Create(() => result, name, $"Fake {name}.");

private static List<string> Names(IEnumerable<AIFunction> tools) => [.. tools.Select(t => t.Name)];

[Fact]
public void NoClash_ReturnsTheSameTools()
{
var read = Fake("read_file");
var query = Fake("query_database");

var result = McpToolNames.Disambiguate([(null, read), ("Sql", query)]);

Assert.Same(read, result[0]);
Assert.Same(query, result[1]);
}

[Fact]
public void TwoServersWithTheSameTool_BothGetTheirServerAsAPrefix()
{
var result = McpToolNames.Disambiguate(
[("Sql", Fake("query_database")), ("Local", Fake("query_database")), ("Local", Fake("list_tables"))]);

Assert.Equal(["Sql_query_database", "Local_query_database", "list_tables"], Names(result));
}

[Fact]
public void ServerToolNamedLikeABuiltIn_IsRenamed_AndTheBuiltInKeepsItsName()
{
var result = McpToolNames.Disambiguate([(null, Fake("read_file")), ("Docs", Fake("read_file"))]);

Assert.Equal(["read_file", "Docs_read_file"], Names(result));
}

[Fact]
public async Task RenamedTool_StillCallsItsOwnTool()
{
var result = McpToolNames.Disambiguate([("Sql", Fake("query", "from sql")), ("Local", Fake("query", "from local"))]);

Assert.Equal("from local", (await result[1].InvokeAsync(new AIFunctionArguments()))?.ToString());
}

// The REPL finds an MCP tool's read-only hint and approval gate through GetService, so a rename must not hide them.
private sealed class Marker(AIFunction inner) : DelegatingAIFunction(inner);

[Fact]
public void RenamedTool_StillAnswersGetServiceForTheWrappersInside()
{
var result = McpToolNames.Disambiguate([("Sql", new Marker(Fake("query"))), ("Local", Fake("query"))]);

Assert.NotNull(result[0].GetService<Marker>());
}

[Fact]
public void ServerNameWithCharactersToolNamesCantHold_IsCleanedUp()
{
var result = McpToolNames.Disambiguate([("my server.v2", Fake("query")), ("other", Fake("query"))]);

Assert.Equal("my_server_v2_query", result[0].Name);
}

[Fact]
public void PrefixedNameTakenByAnotherTool_GetsANumber()
{
var result = McpToolNames.Disambiguate(
[(null, Fake("Sql_query")), ("Sql", Fake("query")), ("Local", Fake("query"))]);

Assert.Equal(["Sql_query", "Sql_query_2", "Local_query"], Names(result));
}

[Fact]
public void LongNames_StayWithinTheProviderLimit_AndUnique()
{
var tool = new string('t', 60);
var server = new string('s', 30);

var result = McpToolNames.Disambiguate([(server, Fake(tool)), (server, Fake(tool))]);

Assert.All(result, t => Assert.True(t.Name.Length <= McpToolNames.MaxLength, t.Name));
Assert.NotEqual(result[0].Name, result[1].Name);
}
}
18 changes: 18 additions & 0 deletions tests/FuseraftCli.Tests/ReplCommandsMcpServerLifecycleTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,22 @@ public async Task Reconnect_UnknownServer_DoesNotTryToConnect()

Assert.Null(ctx.McpManager);
}

[Fact]
public void ServersWithTheSameToolName_AreOfferedUnderNamesTheModelCanTellApart()
{
AIFunction Tool(string name) => AIFunctionFactory.Create(() => "ok", name);
var ctx = NewContext(new(StringComparer.OrdinalIgnoreCase)
{
["FileSystem"] = [Tool("read_file")],
["mcp:Sql"] = [Tool("query_database")],
["mcp:Local"] = [Tool("query_database"), Tool("read_file")],
});

var names = ctx.GetActiveTools().Select(t => t.Name).ToList();
var sent = ctx.ChatOptions!.Tools!.Select(t => t.Name).ToList();

Assert.Equal(["read_file", "Sql_query_database", "Local_query_database", "Local_read_file"], names);
Assert.Equal(names, sent);
}
}
2 changes: 1 addition & 1 deletion tests/FuseraftCli.Tests/SseEventIdleTimeoutStreamTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public async Task SilentSocket_TripsTheConfiguredByteIdleTimeout()
var stream = new SseEventIdleTimeoutStream(
new NeverRespondsStream(), contentIdleTimeout: TimeSpan.FromMinutes(5), byteIdle: TimeSpan.FromMilliseconds(80));

var ex = await Assert.ThrowsAsync<TimeoutException>(async () => await stream.ReadAsync(new byte[16]));
var ex = await Assert.ThrowsAsync<TimeoutException>(async () => await stream.ReadExactlyAsync(new byte[16]));

Assert.Contains("no bytes received", ex.Message);
}
Expand Down
Loading