-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
287 lines (259 loc) · 8.77 KB
/
main.go
File metadata and controls
287 lines (259 loc) · 8.77 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
const (
defaultHTTPAddr = ":8080"
defaultHTTPPath = "/mcp"
)
func readEnv(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
func toExecRelative(p string) (string, error) {
if p == "" {
return "", nil
}
if filepath.IsAbs(p) {
return p, nil
}
exe, err := os.Executable()
if err != nil {
return "", err
}
return filepath.Join(filepath.Dir(exe), p), nil
}
func mustJSON(v any) string {
b, _ := json.MarshalIndent(v, "", " ")
return string(b)
}
func main() {
transport := strings.ToLower(readEnv("TRANSPORT", "stdio"))
httpAddr := readEnv("HTTP_ADDR", defaultHTTPAddr)
httpPath := readEnv("HTTP_PATH", defaultHTTPPath)
memPathEnv := readEnv("MEMORY_FILE_PATH", "memory.db")
boltPathEnv := readEnv("BOLT_DB_PATH", "")
memPath, err := toExecRelative(memPathEnv)
if err != nil {
log.Fatalf("resolve memory path: %v", err)
}
boltPath := boltPathEnv
if boltPath == "" {
boltPath = memPath + ".bolt"
}
boltPath, err = toExecRelative(boltPath)
if err != nil {
log.Fatalf("resolve bolt path: %v", err)
}
mgr := NewGraphManager(memPath, boltPath)
server := mcp.NewServer(&mcp.Implementation{Name: "memory-server", Version: "0.6.3"}, nil)
mcp.AddTool(server, &mcp.Tool{
Name: "create_entities",
Description: "Create multiple new entities in the knowledge graph",
}, func(_ context.Context, _ *mcp.CallToolRequest, in struct {
Entities []Entity `json:"entities"`
}) (*mcp.CallToolResult, any, error) {
created, err := mgr.CreateEntities(in.Entities)
if err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: mustJSON(created)}}}, nil, nil
})
mcp.AddTool(server, &mcp.Tool{
Name: "create_relations",
Description: "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice",
}, func(_ context.Context, _ *mcp.CallToolRequest, in struct {
Relations []Relation `json:"relations"`
}) (*mcp.CallToolResult, any, error) {
created, err := mgr.CreateRelations(in.Relations)
if err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: mustJSON(created)}}}, nil, nil
})
mcp.AddTool(server, &mcp.Tool{
Name: "add_observations",
Description: "Add new observations to existing entities in the knowledge graph",
}, func(_ context.Context, _ *mcp.CallToolRequest, in struct {
Observations []struct {
EntityName string `json:"entityName"`
Contents []string `json:"contents"`
} `json:"observations"`
}) (*mcp.CallToolResult, any, error) {
added, err := mgr.AddObservations(in.Observations)
if err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: mustJSON(added)}}}, nil, nil
})
mcp.AddTool(server, &mcp.Tool{
Name: "delete_entities",
Description: "Delete multiple entities and their associated relations from the knowledge graph",
}, func(_ context.Context, _ *mcp.CallToolRequest, in struct {
EntityNames []string `json:"entityNames"`
}) (*mcp.CallToolResult, any, error) {
if err := mgr.DeleteEntities(in.EntityNames); err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "Entities deleted successfully"}}}, nil, nil
})
mcp.AddTool(server, &mcp.Tool{
Name: "delete_observations",
Description: "Delete specific observations from entities in the knowledge graph",
}, func(_ context.Context, _ *mcp.CallToolRequest, in struct {
Deletions []struct {
EntityName string `json:"entityName"`
Observations []string `json:"observations"`
} `json:"deletions"`
}) (*mcp.CallToolResult, any, error) {
if err := mgr.DeleteObservations(in.Deletions); err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "Observations deleted successfully"}}}, nil, nil
})
mcp.AddTool(server, &mcp.Tool{
Name: "delete_relations",
Description: "Delete multiple relations from the knowledge graph",
}, func(_ context.Context, _ *mcp.CallToolRequest, in struct {
Relations []Relation `json:"relations"`
}) (*mcp.CallToolResult, any, error) {
if err := mgr.DeleteRelations(in.Relations); err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "Relations deleted successfully"}}}, nil, nil
})
mcp.AddTool(server, &mcp.Tool{
Name: "read_graph",
Description: "Read the entire knowledge graph",
}, func(_ context.Context, _ *mcp.CallToolRequest, _ struct{}) (*mcp.CallToolResult, any, error) {
g, err := mgr.ReadGraph()
if err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: mustJSON(g)}}}, nil, nil
})
mcp.AddTool(server, &mcp.Tool{
Name: "search_nodes",
Description: "Search for nodes in the knowledge graph based on a query",
}, func(_ context.Context, _ *mcp.CallToolRequest, in struct {
Query string `json:"query"`
}) (*mcp.CallToolResult, any, error) {
g, err := mgr.SearchNodes(in.Query)
if err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: mustJSON(g)}}}, nil, nil
})
mcp.AddTool(server, &mcp.Tool{
Name: "open_nodes",
Description: "Open specific nodes in the knowledge graph by their names",
}, func(_ context.Context, _ *mcp.CallToolRequest, in struct {
Names []string `json:"names"`
}) (*mcp.CallToolResult, any, error) {
g, err := mgr.OpenNodes(in.Names)
if err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: mustJSON(g)}}}, nil, nil
})
switch transport {
case "stdio":
if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
log.Fatalf("stdio server failed: %v", err)
}
case "http":
addr := httpAddr
path := httpPath
if path == "" {
path = defaultHTTPPath
}
getServer := func(_ *http.Request) *mcp.Server { return server }
h := mcp.NewStreamableHTTPHandler(getServer, &mcp.StreamableHTTPOptions{})
var handler http.Handler = h
user, pass, err := readBasicAuth()
if err != nil {
log.Fatalf("basic auth config error: %v", err)
}
if user != "" || pass != "" {
handler = BasicAuthMiddleware(handler, user, pass)
}
handler = CORSMiddleware(handler)
mux := http.NewServeMux()
mux.Handle(path, handler)
log.Printf("Knowledge Graph MCP Server running on HTTP %s%s", addr, path)
if err := http.ListenAndServe(addr, mux); err != nil {
log.Fatal(err)
}
default:
log.Fatalf("unknown transport: %q (use stdio or http)", transport)
}
}
func readBasicAuth() (string, string, error) {
user := readEnv("BASIC_AUTH_USER", "")
pass := readEnv("BASIC_AUTH_PASSWORD", "")
if uf := readEnv("BASIC_AUTH_USER_FILE", ""); uf != "" {
b, err := os.ReadFile(uf)
if err != nil {
return "", "", err
}
user = strings.TrimSpace(string(b))
}
if pf := readEnv("BASIC_AUTH_PASSWORD_FILE", ""); pf != "" {
b, err := os.ReadFile(pf)
if err != nil {
return "", "", err
}
pass = strings.TrimSpace(string(b))
}
if (user == "") != (pass == "") {
return "", "", errors.New("both BASIC_AUTH_USER and BASIC_AUTH_PASSWORD (or *_FILE) must be set together")
}
return user, pass, nil
}
func BasicAuthMiddleware(next http.Handler, user, pass string) http.Handler {
want := base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Basic ") {
w.Header().Set("WWW-Authenticate", "Basic realm=\"mcp\"")
http.Error(w, "authentication required", http.StatusUnauthorized)
return
}
got := strings.TrimPrefix(auth, "Basic ")
if got != want {
w.Header().Set("WWW-Authenticate", "Basic realm=\"mcp\"")
http.Error(w, "invalid credentials", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func CORSMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Vary", "Origin")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Expose-Headers", "Mcp-Session-Id")
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}