Skip to content

Commit cbf8d4f

Browse files
authored
chore(example): context propagation and signal-based cancellation (google#237)
* refactor(mcp): integrate context propagation and signal-based cancellation - Add signal handling to gracefully cancel the context on interrupt (SIGINT, SIGTERM) - Update functions to accept context instead of creating a new one internally - Pass the main context to MCP transport constructors for improved cancellation support Signed-off-by: appleboy <appleboy.tw@gmail.com> * refactor: improve signal handling and cleanup unused imports - Remove unused import of syscall - Create cancellation context only for SIGINT (Ctrl+C), not SIGTERM Signed-off-by: appleboy <appleboy.tw@gmail.com> * style: adopt Go-style octal file permissions throughout codebase - Use Go-style octal notation (0o) for file permission arguments in os.MkdirAll and os.WriteFile - Remove a few unnecessary blank lines at the end of main functions Signed-off-by: appleboy <appleboy.tw@gmail.com> --------- Signed-off-by: appleboy <appleboy.tw@gmail.com>
1 parent db9205e commit cbf8d4f

File tree

4 files changed

+12
-13
lines changed

4 files changed

+12
-13
lines changed

‎examples/mcp/main.go‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"fmt"
2020
"log"
2121
"os"
22+
"os/signal"
2223
"strings"
2324

2425
"github.com/modelcontextprotocol/go-sdk/mcp"
@@ -58,32 +59,34 @@ func GetWeather(ctx context.Context, req *mcp.CallToolRequest, input Input) (*mc
5859
}, nil
5960
}
6061

61-
func localMCPTransport() mcp.Transport {
62+
func localMCPTransport(ctx context.Context) mcp.Transport {
6263
clientTransport, serverTransport := mcp.NewInMemoryTransports()
6364

6465
// Run in-memory MCP server.
6566
server := mcp.NewServer(&mcp.Implementation{Name: "weather_server", Version: "v1.0.0"}, nil)
6667
mcp.AddTool(server, &mcp.Tool{Name: "get_weather", Description: "returns weather in the given city"}, GetWeather)
67-
_, err := server.Connect(context.Background(), serverTransport, nil)
68+
_, err := server.Connect(ctx, serverTransport, nil)
6869
if err != nil {
6970
log.Fatal(err)
7071
}
7172

7273
return clientTransport
7374
}
7475

75-
func githubMCPTransport() mcp.Transport {
76+
func githubMCPTransport(ctx context.Context) mcp.Transport {
7677
ts := oauth2.StaticTokenSource(
7778
&oauth2.Token{AccessToken: os.Getenv("GITHUB_PAT")},
7879
)
7980
return &mcp.StreamableClientTransport{
8081
Endpoint: "https://api.githubcopilot.com/mcp/",
81-
HTTPClient: oauth2.NewClient(context.Background(), ts),
82+
HTTPClient: oauth2.NewClient(ctx, ts),
8283
}
8384
}
8485

8586
func main() {
86-
ctx := context.Background()
87+
// Create context that cancels on interrupt signal (Ctrl+C)
88+
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
89+
defer stop()
8790

8891
model, err := gemini.NewModel(ctx, "gemini-2.5-flash", &genai.ClientConfig{
8992
APIKey: os.Getenv("GOOGLE_API_KEY"),
@@ -94,9 +97,9 @@ func main() {
9497

9598
var transport mcp.Transport
9699
if strings.ToLower(os.Getenv("AGENT_MODE")) == "github" {
97-
transport = githubMCPTransport()
100+
transport = githubMCPTransport(ctx)
98101
} else {
99-
transport = localMCPTransport()
102+
transport = localMCPTransport(ctx)
100103
}
101104

102105
mcpToolSet, err := mcptoolset.New(mcptoolset.Config{
@@ -128,5 +131,4 @@ func main() {
128131
if err != nil {
129132
log.Fatalf("run failed: %v\n\n%s", err, l.CommandLineSyntax())
130133
}
131-
132134
}

‎examples/vertexai/imagegenerator/main.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,13 +159,13 @@ func saveImage(ctx tool.Context, input saveImageInput) saveImageResult {
159159

160160
// Create an "output" directory in the current working directory if it doesn't exist.
161161
outputDir := "output"
162-
if err := os.MkdirAll(outputDir, 0755); err != nil {
162+
if err := os.MkdirAll(outputDir, 0o755); err != nil {
163163
log.Printf("Failed to create output directory '%s': %v", outputDir, err)
164164
return saveImageResult{Status: "fail"}
165165
}
166166

167167
localPath := filepath.Join(outputDir, localFilename)
168-
err = os.WriteFile(localPath, resp.Part.InlineData.Data, 0644)
168+
err = os.WriteFile(localPath, resp.Part.InlineData.Data, 0o644)
169169
if err != nil {
170170
log.Printf("Failed to write image to local file '%s': %v", localPath, err)
171171
return saveImageResult{Status: "fail"}

‎examples/workflowagents/sequential/main.go‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,5 +92,4 @@ func main() {
9292
if err != nil {
9393
log.Fatalf("run failed: %v\n\n%s", err, l.CommandLineSyntax())
9494
}
95-
9695
}

‎examples/workflowagents/sequentialCode/main.go‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ import (
3030
)
3131

3232
func main() {
33-
3433
ctx := context.Background()
3534

3635
model, err := gemini.NewModel(ctx, "gemini-2.5-flash", &genai.ClientConfig{})
@@ -148,5 +147,4 @@ Do not add any other text before or after the code block.`,
148147
if err != nil {
149148
log.Fatalf("run failed: %v\n\n%s", err, l.CommandLineSyntax())
150149
}
151-
152150
}

0 commit comments

Comments
 (0)