-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapter_mcp.go
More file actions
93 lines (82 loc) · 2.35 KB
/
adapter_mcp.go
File metadata and controls
93 lines (82 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package kuniumi
import (
"context"
"encoding/json"
"fmt"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/spf13/cobra"
)
func (a *App) buildMcpCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "mcp",
Short: "Run as a Model Context Protocol (MCP) server",
RunE: func(cmd *cobra.Command, args []string) error {
// Create MCP Server
s := mcp.NewServer(&mcp.Implementation{
Name: a.config.Name,
Version: a.config.Version,
}, nil)
// Register Tools
for _, fn := range a.functions {
tool := mcp.Tool{
Name: fn.OperationID(),
Description: fn.Description,
InputSchema: GenerateJSONSchema(fn.Meta),
}
// Capture closure variables
targetFn := fn
s.AddTool(&tool, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
// req.Params.Arguments is json.RawMessage
params := req.Params
var toolArgs map[string]any
// Handle nil or empty arguments
if len(params.Arguments) > 0 {
if err := json.Unmarshal(params.Arguments, &toolArgs); err != nil {
errJSON, _ := json.Marshal(buildErrorResponse(fmt.Sprintf("Invalid arguments format: %v", err)))
return &mcp.CallToolResult{
IsError: true,
Content: []mcp.Content{
&mcp.TextContent{Text: string(errJSON)},
},
}, nil
}
} else {
toolArgs = make(map[string]interface{})
}
// Create context with env
appCtx := a.ContextWithEnv(ctx)
results, err := CallFunction(appCtx, targetFn.Meta, toolArgs)
if err != nil {
errJSON, _ := json.Marshal(buildErrorResponse(err.Error()))
return &mcp.CallToolResult{
IsError: true,
Content: []mcp.Content{
&mcp.TextContent{Text: string(errJSON)},
},
}, nil
}
response := buildSuccessResponse(results)
jsonBytes, marshalErr := json.Marshal(response)
if marshalErr != nil {
return &mcp.CallToolResult{
IsError: true,
Content: []mcp.Content{
&mcp.TextContent{Text: `{"error":"failed to marshal response"}`},
},
}, nil
}
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: string(jsonBytes)},
},
}, nil
})
}
// Serve StdIO
// Using StdioTransport
transport := &mcp.StdioTransport{}
return s.Run(cmd.Context(), transport)
},
}
return cmd
}