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
20 changes: 3 additions & 17 deletions src/Everywhere.Core/Chat/Plugins/ChatFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
using System.Reflection;
using CommunityToolkit.Mvvm.ComponentModel;
using Everywhere.Chat.Permissions;
using Everywhere.Chat.Plugins.Mcp;
using Lucide.Avalonia;
using Microsoft.SemanticKernel;
using ModelContextProtocol.Client;
using ZLinq;

namespace Everywhere.Chat.Plugins;
Expand Down Expand Up @@ -128,29 +128,15 @@ public NativeChatFunction(
}
}

public sealed class McpChatFunction : ChatFunction
public class McpChatFunction : ChatFunction
{
public override ChatFunctionPermissions Permissions => ChatFunctionPermissions.MCP;

public override KernelFunction KernelFunction { get; }

public McpChatFunction(McpClientTool tool)
public McpChatFunction(ManagedMcpClientTool tool)
{
KernelFunction = tool.AsKernelFunction();
IsAutoApproveAllowed = true;
}

/// <summary>
/// MCP tool name SHOULD only allow: uppercase and lowercase ASCII letters (A-Z, a-z), digits (0-9), underscore (_), hyphen (-), and dot (.)
/// But SK only allow ASCII letters, digits, and underscores in function name, so we need to escape the tool name to make it compatible with SK.
/// </summary>
/// <param name="tool"></param>
private static void EscapeToolName(McpClientTool tool)
{
ref var name = ref GetName(tool);
name = new string(name.AsValueEnumerable().Select(c => char.IsLetterOrDigit(c) ? c : '_').ToArray());
}

[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_name")]
private static extern ref string GetName(McpClientTool tool);
}
196 changes: 10 additions & 186 deletions src/Everywhere.Core/Chat/Plugins/ChatPluginManager.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reactive.Disposables;
using System.Text;
using DynamicData;
using Everywhere.Chat.Permissions;
using Everywhere.Chat.Plugins.Mcp;
using Everywhere.Collections;
using Everywhere.Common;
using Everywhere.Configuration;
using Everywhere.Initialization;
using Everywhere.Interop;
using Everywhere.Utilities;
using FuzzySharp;
using Lucide.Avalonia;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using ZLinq;

namespace Everywhere.Chat.Plugins;
Expand All @@ -30,12 +27,11 @@ public class ChatPluginManager : IChatPluginManager
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILoggerFactory _loggerFactory;
private readonly Settings _settings;
private readonly ILogger<ChatPluginManager> _logger;

private readonly CompositeDisposable _disposables = new();
private readonly SourceList<BuiltInChatPlugin> _builtInPluginsSource = new();
private readonly SourceList<McpChatPlugin> _mcpPluginsSource = new();
private readonly ConcurrentDictionary<Guid, McpClient> _runningMcpClients = [];
private readonly ConcurrentDictionary<Guid, ManagedMcpClient> _startedMcpClients = [];

public ChatPluginManager(
IEnumerable<BuiltInChatPlugin> builtInPlugins,
Expand All @@ -49,7 +45,6 @@ public ChatPluginManager(
_httpClientFactory = httpClientFactory;
_loggerFactory = loggerFactory;
_settings = settings;
_logger = loggerFactory.CreateLogger<ChatPluginManager>();

// Load MCP plugins from settings.
_mcpPluginsSource.AddRange(settings.Plugin.McpChatPlugins.Select(m => m.ToMcpChatPlugin()).OfType<McpChatPlugin>());
Expand Down Expand Up @@ -217,10 +212,9 @@ public async Task UpdateMcpPluginAsync(McpChatPlugin mcpChatPlugin, McpTransport

public async Task StopMcpClientAsync(McpChatPlugin mcpChatPlugin)
{
if (_runningMcpClients.TryRemove(mcpChatPlugin.Id, out var runningClient))
if (_startedMcpClients.TryRemove(mcpChatPlugin.Id, out var runningClient))
{
await runningClient.DisposeAsync();
mcpChatPlugin.IsRunning = false;
}
}

Expand All @@ -246,104 +240,10 @@ public async Task StartMcpClientAsync(McpChatPlugin mcpChatPlugin, CancellationT
new DynamicResourceKey(LocaleKey.ChatPluginManager_Common_InvalidMcpTransportConfiguration));
}

if (_runningMcpClients.ContainsKey(mcpChatPlugin.Id)) return; // Just return without error if already running.

var loggerFactory = new McpLoggerFactory(mcpChatPlugin, _loggerFactory);
IClientTransport clientTransport = transportConfiguration switch
{
StdioMcpTransportConfiguration stdio => new StdioClientTransport(
new StdioClientTransportOptions
{
Name = stdio.Name,
Command = stdio.Command,
Arguments = stdio.Arguments
.AsValueEnumerable()
.Select(x => x.Value)
.Where(x => !x.IsNullOrWhiteSpace())
.ToList(),
WorkingDirectory = EnsureWorkingDirectory(stdio.WorkingDirectory),
EnvironmentVariables = EnsureLatestPath(
stdio.EnvironmentVariables
.AsValueEnumerable()
.Where(kv => !kv.Key.IsNullOrWhiteSpace())
.DistinctBy(
kv => kv.Key,
OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal)
.ToDictionary(
kv => kv.Key,
kv => kv.Value,
OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal)),
},
loggerFactory),
HttpMcpTransportConfiguration sse => new HttpClientTransport(
new HttpClientTransportOptions
{
Name = sse.Name,
Endpoint = new Uri(sse.Endpoint, UriKind.Absolute),
AdditionalHeaders = sse.Headers
.AsValueEnumerable()
.Where(kv => !kv.Key.IsNullOrWhiteSpace() && !kv.Value.IsNullOrWhiteSpace())
.DistinctBy(kv => kv.Key)
.ToDictionary(kv => kv.Key, kv => kv.Value),
TransportMode = sse.TransportMode
},
_httpClientFactory.CreateClient(NetworkExtension.JsonRpcClientName),
loggerFactory),
_ =>
throw new HandledException(
new InvalidOperationException("Unsupported MCP transport configuration type."),
new DynamicResourceKey(LocaleKey.ChatPluginManager_Common_InvalidMcpTransportConfiguration))
};

var client = await McpClient.CreateAsync(
clientTransport,
null,
loggerFactory,
cancellationToken);

// Store the running client.
_runningMcpClients[mcpChatPlugin.Id] = client;
mcpChatPlugin.IsRunning = true;

var processId = -1;
try
{
if (clientTransport is StdioClientTransport)
{
// Add the underlying process to the watchdog to ensure it is cleaned up properly.
// We need reflection here because StdioClientTransport does not expose the process directly.
// client is `ModelContextProtocol.Client.McpClientImpl`
var transport = GetMcpClientTransport(client);
if (GetStdioClientSessionTransportProcess(transport) is { HasExited: false, Id: > 0 } process)
{
process.Exited += HandleProcessExited;

void HandleProcessExited(object? sender, EventArgs e)
{
mcpChatPlugin.IsRunning = false;
_runningMcpClients.TryRemove(mcpChatPlugin.Id, out _);
process.Exited -= HandleProcessExited;
}

await _watchdogManager.RegisterProcessAsync(process.Id);
processId = process.Id;
}
}
}
finally
{
if (processId == -1 && transportConfiguration is StdioMcpTransportConfiguration stdio)
{
_logger.LogWarning(
"MCP started with stdio transport, but failed to get the underlying process ID for watchdog registration. " +
"Command: {Command}, Arguments: {Arguments}",
stdio.Command,
stdio.Arguments);
}
}

var tools = await client.ListToolsAsync(cancellationToken: cancellationToken);
var client = await ManagedMcpClient.StartAsync(mcpChatPlugin, _httpClientFactory, _watchdogManager, _loggerFactory, cancellationToken);
_startedMcpClients[mcpChatPlugin.Id] = client;

var tools = await client.ListToolsAsync(cancellationToken);
var isEnabledRecords = _settings.Plugin.IsEnabledRecords;
var isPermissionGrantedRecords = _settings.Plugin.IsPermissionGrantedRecords;
mcpChatPlugin.SetFunctions(
Expand All @@ -352,33 +252,6 @@ void HandleProcessExited(object? sender, EventArgs e)
IsEnabled = !isEnabledRecords.TryGetValue(t.Name, out var isEnabled) || isEnabled, // true if not set
AutoApprove = isPermissionGrantedRecords.TryGetValue(t.Name, out var isGranted) && isGranted, // false if not set
}));

string EnsureWorkingDirectory(string? workingDirectory)
{
if (Directory.Exists(workingDirectory)) return workingDirectory;

// If not exists, fall back to Everywhere\cache\plugins\mcp\<plugin-id>
var fallbackDir = RuntimeConstants.EnsureWritableDataFolderPath("plugins", "mcp", mcpChatPlugin.Id.ToString("N"));
return fallbackDir;
}

Dictionary<string, string?> EnsureLatestPath(Dictionary<string, string?> environmentVariables)
{
var latestPath = EnvironmentVariableUtilities.GetLatestPathVariable();
if (latestPath.IsNullOrEmpty()) return environmentVariables;

// Put our latest PATH at the front.
var pathBuilder = new StringBuilder(latestPath);

// Append existing PATH variable if any.
if (environmentVariables.TryGetValue("PATH", out var existingPath) && !existingPath.IsNullOrEmpty())
{
pathBuilder.Append(Path.PathSeparator).Append(existingPath);
}

environmentVariables["PATH"] = pathBuilder.ToString();
return environmentVariables;
}
}

public async Task<IChatPluginScope> CreateScopeAsync(bool isSubagent, CancellationToken cancellationToken)
Expand Down Expand Up @@ -419,14 +292,6 @@ public async Task<IChatPluginScope> CreateScopeAsync(bool isSubagent, Cancellati
.ToList());
}

[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_transport")]
private static extern ref ITransport GetMcpClientTransport(
[UnsafeAccessorType("ModelContextProtocol.Client.McpClientImpl, ModelContextProtocol.Core")] object client);

[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_process")]
private static extern ref Process GetStdioClientSessionTransportProcess(
[UnsafeAccessorType("ModelContextProtocol.Client.StdioClientSessionTransport, ModelContextProtocol.Core")] object transport);

private class ChatPluginScope(List<ChatPluginSnapshot> pluginSnapshots) : IChatPluginScope
{
public IReadOnlyList<ChatPlugin> Plugins => pluginSnapshots;
Expand All @@ -450,7 +315,7 @@ public bool TryGetPluginAndFunction(

plugin = null;
function = null;
similarFunctionNames = FuzzySharp.Process.ExtractTop(
similarFunctionNames = Process.ExtractTop(
functionName,
pluginSnapshots.SelectMany(p => p.Functions).Select(f => f.KernelFunction.Name),
limit: 5)
Expand Down Expand Up @@ -504,11 +369,11 @@ ChatFunction EnsureUniqueFunctionName(ChatFunction function)

public void Dispose()
{
foreach (var mcpClient in _runningMcpClients.Values)
foreach (var mcpClient in _startedMcpClients.Values)
{
mcpClient.DisposeAsync().Detach(IExceptionHandler.DangerouslyIgnoreAllException);
}
_runningMcpClients.Clear();
_startedMcpClients.Clear();

_mcpPluginsSource.Edit(items =>
{
Expand All @@ -519,45 +384,4 @@ public void Dispose()
});
_disposables.Dispose();
}

/// <summary>
/// Used to create ILogger instances for MCP clients.
/// It logs to both the Everywhere logging system and the <see cref="McpChatPlugin"/>'s log entries.
/// </summary>
private sealed class McpLoggerFactory(McpChatPlugin mcpChatPlugin, ILoggerFactory innerLoggerFactory) : ILoggerFactory
{
public void AddProvider(ILoggerProvider provider)
{
innerLoggerFactory.AddProvider(provider);
}

public ILogger CreateLogger(string categoryName)
{
var innerLogger = innerLoggerFactory.CreateLogger(categoryName);
return new McpLogger(mcpChatPlugin, innerLogger);
}

public void Dispose()
{
innerLoggerFactory.Dispose();
}

private sealed class McpLogger(ILogger mcpChatPlugin, ILogger innerLogger) : ILogger
{
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => innerLogger.BeginScope(state);

public bool IsEnabled(LogLevel logLevel) => true;

public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
mcpChatPlugin.Log(logLevel, eventId, state, exception, formatter);
innerLogger.Log(logLevel, eventId, state, exception, formatter);
}
}
}
}
Loading
Loading