From 1773cc7ef1ccce435f6ff76dab8b5b69efbaa6c8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 1 May 2026 10:20:36 -0700 Subject: [PATCH] perf(mcp): eliminate LINQ and ToArray() allocations in McpToolBridge (#243) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/OpenClaw.Shared/Mcp/McpToolBridge.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/OpenClaw.Shared/Mcp/McpToolBridge.cs b/src/OpenClaw.Shared/Mcp/McpToolBridge.cs index 5710854..3957c8b 100644 --- a/src/OpenClaw.Shared/Mcp/McpToolBridge.cs +++ b/src/OpenClaw.Shared/Mcp/McpToolBridge.cs @@ -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; @@ -259,7 +258,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}"); @@ -316,7 +321,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) @@ -333,7 +338,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); } ///