Skip to content

Add context cancellation checks to MCP tool handlers - #6311

Merged
pelikhan merged 2 commits into
mainfrom
copilot/add-context-cancellation-checks
Dec 13, 2025
Merged

pelikhan merged 2 commits into
mainfrom
copilot/add-context-cancellation-checks

Conversation

Copilot AI commented Dec 13, 2025 •

Copy link
Copy Markdown
Contributor

MCP tool handlers receive a context but don't check for cancellation before performing I/O and subprocess operations. This causes handlers to continue executing after client disconnection.

Changes

  • Added ctx.Done() checks to all 7 tool handlers (status, compile, logs, audit, mcp-inspect, add, update)
  • Added second check in compile handler after Docker image preparation (potentially slow operation)
  • Returns ctx.Err() when cancellation detected

Implementation

select {
case <-ctx.Done():
    return &mcp.CallToolResult{
        Content: []mcp.Content{
            &mcp.TextContent{Text: fmt.Sprintf("Error: %v", ctx.Err())},
        },
    }, nil, nil
default:
}

Subprocess commands already use exec.CommandContext(ctx, ...) so cancellation propagates automatically. The explicit checks provide early exit before spawning processes.

Test Coverage

Added TestMCPServer_ContextCancellation that validates handlers exit gracefully with pre-cancelled contexts.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • https://api.github.com/user
    • Triggering command: /usr/bin/gh gh api user --jq .login --show-toplevel ache/go/1.25.0/x64/pkg/tool/linurefs/tags/v2 9de148c36c6c1b17c9aae9dba1805ed669d1c62fda11916fa64/log.json te (http block)
    • Triggering command: /usr/bin/gh gh api user --jq .login (http block)
    • Triggering command: /usr/bin/gh gh api user --jq .login /run/containerd/io.containerd.runtime.v2.task/moby/9f6ba46a12b0f14a9562a2613f217cff8f5bee92d819d1e648afd9d30f4aff72/init.pid 9f6ba46a12b0f14a9562a2613f217cff8f5bee92d819d1e648afd9d30f4aff72 4768951/b356=&gt; -unreachable=fal/usr/bin/jq /tmp/go-build611.[0] 199435/b327/vet.cfg sh -c mplates from .github to pkg/cli/templates...&#34; /opt/hostedtoolcache/go/1.25.0/x64/pkg/tool/linu/home/REDACTED/work/gh-aw/gh-aw/pkg/logger/logger.status /usr/bin/git -unreachable=falgrep /tmp/go-build611-q /opt/hostedtoolccreate git (http block)

If you need me to access, download, or install something from one of these locations, you can either:

Original prompt

This section details on the original issue you should resolve

<issue_title>[plan] Add context cancellation checks to MCP tool handlers</issue_title>
<issue_description>## Objective

Add context cancellation checks to MCP tool handlers to properly handle client disconnections and cancelled operations.

Context

Currently, MCP tool handlers receive a context but don't check for cancellation. Adding ctx.Done() checks before long-running operations will improve resource management and allow tools to exit early when clients disconnect.

Approach

  1. Identify tool handlers in pkg/cli/mcp_server.go that perform long-running operations
  2. Add context cancellation checks at appropriate points
  3. Return early with context error when cancelled

Example Pattern

func handleLongRunningTool(ctx context.Context, params ToolParams) (string, error) {
    // Check for cancellation before starting
    select {
    case <-ctx.Done():
        return "", ctx.Err()
    default:
    }
    
    // Perform work...
    result := performWork()
    
    // Check again before next step
    select {
    case <-ctx.Done():
        return "", ctx.Err()
    default:
    }
    
    return result, nil
}

Files to Modify

  • pkg/cli/mcp_server.go - Add context checks to tool handlers that perform I/O or exec operations

Acceptance Criteria

  • Tool handlers check ctx.Done() before significant operations
  • Cancelled operations return ctx.Err() promptly
  • Normal tool invocations continue to work
  • Tests pass: make test
  • Manual test: Tool responds to cancellation (e.g., interrupt during execution)
    Related to [plan] Adopt MCP Go SDK v1.1.0 improvements #6249

AI generated by Plan Command for discussion #6222

Comments on the Issue (you are @copilot in this section)


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Co-authored-by: mnkiefer <8320933+mnkiefer@users.noreply.github.com>
Copilot AI changed the title [WIP] Add context cancellation checks to MCP tool handlers Add context cancellation checks to MCP tool handlers Dec 13, 2025
Copilot AI requested a review from mnkiefer December 13, 2025 02:00
@pelikhan
pelikhan marked this pull request as ready for review December 13, 2025 08:19
@pelikhan
pelikhan merged commit e4bd6a9 into main Dec 13, 2025
161 checks passed
@pelikhan
pelikhan deleted the copilot/add-context-cancellation-checks branch December 13, 2025 08:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[plan] Add context cancellation checks to MCP tool handlers

3 participants