-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
82 lines (68 loc) · 1.83 KB
/
Copy pathserver.go
File metadata and controls
82 lines (68 loc) · 1.83 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
package mcp
import (
"context"
"encoding/json"
"errors"
"strings"
"github.com/invopop/jsonschema"
)
type Server struct {
name string
tools []internalToolT
}
type internalToolT struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema *jsonschema.Schema `json:"inputSchema"`
Handler func(arguments json.RawMessage, ctx context.Context) (any, error) `json:"-"`
}
type Tool[T any] struct {
// Required fields
Name string
Description string
Handler func(arguments T, ctx context.Context) (any, error)
// Not required
args T
}
func NewServer(name string) *Server {
return &Server{
name: name,
tools: []internalToolT{},
}
}
func AddToolToServer[T any](server *Server, tool Tool[T]) {
err := TryAddToolToServer(server, tool)
if err != nil {
panic(err)
}
}
func TryAddToolToServer[T any](server *Server, tool Tool[T]) error {
tool.Name = strings.TrimSpace(tool.Name)
if tool.Name == "" {
return errors.New("tool has no name")
}
tool.Description = strings.TrimSpace(tool.Description)
if tool.Description == "" {
return errors.New("tool has no description")
}
inputSchema := (&jsonschema.Reflector{
DoNotReference: true,
}).Reflect(tool.args)
if tool.Handler == nil {
return errors.New("tool has no handler")
}
server.tools = append(server.tools, internalToolT{
Name: tool.Name,
Description: tool.Description,
InputSchema: inputSchema,
Handler: func(rawArguments json.RawMessage, ctx context.Context) (any, error) {
var arguments T
err := json.Unmarshal(rawArguments, &arguments)
if err != nil {
return nil, err
}
return tool.Handler(arguments, ctx)
},
})
return nil
}