perf(mcp): eliminate LINQ and ToArray() allocations in McpToolBridge

- Remove System.Linq import; replace FirstOrDefault with foreach loop
  in HandleToolsCallAsync — avoids delegate allocation on every tool call
- Replace ms.ToArray() with ms.GetBuffer() + slice in WriteResult and
  WriteError — avoids copying the byte array before UTF-8 decoding

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
github-actions[bot] 2026-04-29 13:10:19 +00:00 committed by GitHub
parent c7630fa008
commit b0418f5db8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
@ -187,7 +186,13 @@ public class McpToolBridge
}
var caps = _capabilityProvider();
var capability = caps.FirstOrDefault(c => c.CanHandle(name));
INodeCapability? capability = null;
foreach (var c in caps)
{
if (!c.CanHandle(name)) continue;
capability = c;
break;
}
if (capability == null)
throw new McpToolException($"Unknown tool: {name}");
@ -244,7 +249,7 @@ public class McpToolBridge
JsonSerializer.Serialize(w, result, PayloadJsonOptions);
w.WriteEndObject();
}
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
return System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
}
private static string WriteError(JsonElement? id, int code, string message)
@ -261,7 +266,7 @@ public class McpToolBridge
w.WriteEndObject();
w.WriteEndObject();
}
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
return System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
}
/// <summary>