-
Notifications
You must be signed in to change notification settings - Fork 366
fix: reduce retained tool output memory #2854
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -160,6 +160,11 @@ type Toolset struct { | |
|
|
||
| supervisor *lifecycle.Supervisor | ||
|
|
||
| // mediaDir is the toolset-scoped temp dir holding spooled media | ||
| // payloads. Created lazily on first spool, removed by Stop. | ||
| mediaMu sync.Mutex | ||
| mediaDir string | ||
|
|
||
| mu sync.Mutex | ||
|
|
||
| // Cached tools and prompts, invalidated via MCP notifications and | ||
|
|
@@ -426,6 +431,7 @@ func (ts *Toolset) Start(ctx context.Context) error { | |
| // Stop tears the supervisor down. Idempotent. | ||
| func (ts *Toolset) Stop(ctx context.Context) error { | ||
| slog.DebugContext(ctx, "Stopping MCP toolset", "server", ts.logID) | ||
| defer ts.cleanupMediaDir() | ||
| if ts.supervisor == nil { | ||
| return nil | ||
| } | ||
|
|
@@ -694,7 +700,7 @@ func (ts *Toolset) callTool(ctx context.Context, toolCall tools.ToolCall) (*tool | |
| return nil, fmt.Errorf("failed to call tool: %w", err) | ||
| } | ||
|
|
||
| result := processMCPContent(resp) | ||
| result := ts.processMCPContent(resp) | ||
| slog.DebugContext(ctx, "MCP tool call completed", "tool", toolCall.Function.Name, "output_length", len(result.Output)) | ||
| slog.DebugContext(ctx, result.Output) | ||
| return result, nil | ||
|
|
@@ -714,7 +720,13 @@ func isInitNotificationSendError(err error) bool { | |
| return false | ||
| } | ||
|
|
||
| func processMCPContent(toolResult *mcp.CallToolResult) *tools.ToolCallResult { | ||
| const maxInlineMediaBytes = 256 * 1024 | ||
|
|
||
| // writeMediaFile is a package-level indirection so tests can simulate | ||
| // disk failures without manipulating the filesystem. | ||
| var writeMediaFile = defaultWriteMediaFile | ||
|
|
||
| func (ts *Toolset) processMCPContent(toolResult *mcp.CallToolResult) *tools.ToolCallResult { | ||
| var text strings.Builder | ||
| var images, audios []tools.MediaContent | ||
|
|
||
|
|
@@ -723,9 +735,9 @@ func processMCPContent(toolResult *mcp.CallToolResult) *tools.ToolCallResult { | |
| case *mcp.TextContent: | ||
| text.WriteString(c.Text) | ||
| case *mcp.ImageContent: | ||
| images = append(images, encodeMedia(c.Data, c.MIMEType)) | ||
| images = append(images, ts.encodeMedia(c.Data, c.MIMEType)) | ||
| case *mcp.AudioContent: | ||
| audios = append(audios, encodeMedia(c.Data, c.MIMEType)) | ||
| audios = append(audios, ts.encodeMedia(c.Data, c.MIMEType)) | ||
| case *mcp.ResourceLink: | ||
| if c.Name != "" { | ||
| // Escape ] in name and ) in URI to prevent broken markdown links. | ||
|
|
@@ -760,12 +772,94 @@ func processMCPContent(toolResult *mcp.CallToolResult) *tools.ToolCallResult { | |
| } | ||
| } | ||
|
|
||
| // encodeMedia re-encodes raw bytes (as decoded by the MCP SDK) back to base64 | ||
| // for our internal MediaContent representation. | ||
| func encodeMedia(data []byte, mimeType string) tools.MediaContent { | ||
| return tools.MediaContent{ | ||
| Data: base64.StdEncoding.EncodeToString(data), | ||
| MimeType: mimeType, | ||
| // encodeMedia keeps small payloads inline and spools larger ones to disk so the | ||
| // session and TUI do not retain duplicate base64 copies. Spooled files live | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If this is a TUI issue then the code should live in the TUI and not deep down in our tools code. Especiually since a filesystem can go away while you are not looking |
||
| // under a toolset-scoped temp directory removed by Stop. | ||
| func (ts *Toolset) encodeMedia(data []byte, mimeType string) tools.MediaContent { | ||
| media := tools.MediaContent{MimeType: mimeType} | ||
| if len(data) <= maxInlineMediaBytes { | ||
| media.Data = base64.StdEncoding.EncodeToString(data) | ||
| return media | ||
| } | ||
|
|
||
| dir, err := ts.ensureMediaDir() | ||
| if err == nil { | ||
| var path string | ||
| path, err = writeMediaFile(dir, data, mimeType) | ||
| if err == nil { | ||
| media.FilePath = path | ||
| return media | ||
| } | ||
| } | ||
| slog.Warn("failed to spool MCP media to disk", "mime_type", mimeType, "bytes", len(data), "error", err) | ||
| media.Data = base64.StdEncoding.EncodeToString(data) | ||
| return media | ||
| } | ||
|
|
||
| // ensureMediaDir lazily creates the toolset-scoped temp dir for spooled | ||
| // media payloads. The directory is removed by Stop. | ||
| func (ts *Toolset) ensureMediaDir() (string, error) { | ||
| ts.mediaMu.Lock() | ||
| defer ts.mediaMu.Unlock() | ||
| if ts.mediaDir != "" { | ||
| return ts.mediaDir, nil | ||
| } | ||
| dir, err := os.MkdirTemp("", "docker-agent-mcp-media-*") | ||
| if err != nil { | ||
|
dgageot marked this conversation as resolved.
|
||
| return "", err | ||
| } | ||
| ts.mediaDir = dir | ||
| return dir, nil | ||
| } | ||
|
|
||
| // cleanupMediaDir removes the toolset-scoped media spool directory, if any. | ||
| func (ts *Toolset) cleanupMediaDir() { | ||
| ts.mediaMu.Lock() | ||
| dir := ts.mediaDir | ||
| ts.mediaDir = "" | ||
| ts.mediaMu.Unlock() | ||
| if dir == "" { | ||
| return | ||
| } | ||
| if err := os.RemoveAll(dir); err != nil { | ||
| slog.Warn("failed to remove MCP media spool directory", "dir", dir, "error", err) | ||
| } | ||
| } | ||
|
|
||
| func defaultWriteMediaFile(dir string, data []byte, mimeType string) (string, error) { | ||
| f, err := os.CreateTemp(dir, "media-*"+mediaExtension(mimeType)) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| path := f.Name() | ||
| if _, err := f.Write(data); err != nil { | ||
| _ = f.Close() | ||
| _ = os.Remove(path) | ||
| return "", err | ||
| } | ||
| if err := f.Close(); err != nil { | ||
| _ = os.Remove(path) | ||
| return "", err | ||
| } | ||
| return path, nil | ||
| } | ||
|
|
||
| func mediaExtension(mimeType string) string { | ||
| switch mimeType { | ||
| case "image/png": | ||
| return ".png" | ||
| case "image/jpeg": | ||
| return ".jpg" | ||
| case "image/gif": | ||
| return ".gif" | ||
| case "image/webp": | ||
| return ".webp" | ||
| case "audio/wav", "audio/wave", "audio/x-wav": | ||
| return ".wav" | ||
| case "audio/mpeg", "audio/mp3": | ||
| return ".mp3" | ||
| default: | ||
| return ".bin" | ||
| } | ||
| } | ||
|
|
||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.