-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
558 lines (488 loc) · 15.7 KB
/
Copy pathmain.go
File metadata and controls
558 lines (488 loc) · 15.7 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"golang.org/x/oauth2"
"google.golang.org/api/option"
"google.golang.org/api/tasks/v1"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
mux := http.NewServeMux()
mcpHandler := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
token := extractBearerToken(r)
if token == "" {
log.Printf("Unauthorized request: missing Bearer token from %s", r.RemoteAddr)
return nil
}
svc, err := newTasksService(r.Context(), token)
if err != nil {
log.Printf("Failed to create Tasks service: %v", err)
return nil
}
server := mcp.NewServer(
&mcp.Implementation{Name: "agentic-layer/mcp-server-gtasks", Version: "0.1.0"},
nil,
)
server.AddReceivingMiddleware(loggingMiddleware)
registerTools(server, svc)
registerResources(server, svc)
return server
}, nil)
mux.HandleFunc("/mcp", func(w http.ResponseWriter, r *http.Request) {
if extractBearerToken(r) == "" {
w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token"`)
http.Error(w, "Unauthorized: missing Bearer token", http.StatusUnauthorized)
return
}
mcpHandler.ServeHTTP(w, r)
})
log.Printf("MCP server listening on :%s", port)
log.Printf(" MCP endpoint: http://localhost:%s/mcp", port)
if err := http.ListenAndServe(":"+port, accessLogMiddleware(mux)); err != nil {
log.Fatalf("Server error: %v", err)
}
}
// accessLogMiddleware logs each HTTP request with method, path, status, and duration.
func accessLogMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lw := &loggingResponseWriter{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(lw, r)
log.Printf("HTTP %s %s %d %s %s", r.Method, r.URL.Path, lw.status, time.Since(start), r.RemoteAddr)
})
}
type loggingResponseWriter struct {
http.ResponseWriter
status int
wroteHeader bool
}
func (w *loggingResponseWriter) WriteHeader(status int) {
if !w.wroteHeader {
w.status = status
w.wroteHeader = true
}
w.ResponseWriter.WriteHeader(status)
}
func (w *loggingResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.wroteHeader = true
}
return w.ResponseWriter.Write(b)
}
func (w *loggingResponseWriter) Flush() {
if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
// loggingMiddleware logs each incoming MCP method call with its duration and any error.
// For tools/call, the tool name is included.
func loggingMiddleware(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
start := time.Now()
detail := mcpRequestDetail(method, req)
result, err := next(ctx, method, req)
if err != nil {
log.Printf("MCP %s%s failed in %s: %v", method, detail, time.Since(start), err)
} else {
log.Printf("MCP %s%s ok in %s", method, detail, time.Since(start))
}
return result, err
}
}
func mcpRequestDetail(method string, req mcp.Request) string {
if method != "tools/call" {
return ""
}
params, ok := req.GetParams().(*mcp.CallToolParamsRaw)
if !ok || params == nil {
return ""
}
if len(params.Arguments) == 0 {
return fmt.Sprintf(" tool=%s", params.Name)
}
return fmt.Sprintf(" tool=%s args=%s", params.Name, params.Arguments)
}
func newTasksService(ctx context.Context, accessToken string) (*tasks.Service, error) {
tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken})
return tasks.NewService(ctx, option.WithTokenSource(tokenSource))
}
func extractBearerToken(r *http.Request) string {
auth := r.Header.Get("Authorization")
if strings.HasPrefix(auth, "Bearer ") {
return strings.TrimPrefix(auth, "Bearer ")
}
return ""
}
// --- Tool Definitions ---
type SearchInput struct {
Query string `json:"query" jsonschema:"Search query"`
}
type ListInput struct {
Cursor string `json:"cursor,omitempty" jsonschema:"Cursor for pagination"`
}
type CreateInput struct {
TaskListID string `json:"taskListId,omitempty" jsonschema:"Task list ID (defaults to @default)"`
Title string `json:"title" jsonschema:"Task title"`
Notes string `json:"notes,omitempty" jsonschema:"Task notes"`
Due string `json:"due,omitempty" jsonschema:"Due date (RFC 3339)"`
}
type UpdateInput struct {
ID string `json:"id" jsonschema:"Task ID"`
TaskListID string `json:"taskListId,omitempty" jsonschema:"Task list ID (defaults to @default)"`
Title string `json:"title,omitempty" jsonschema:"Task title"`
Notes string `json:"notes,omitempty" jsonschema:"Task notes"`
Status string `json:"status,omitempty" jsonschema:"Task status: needsAction or completed"`
Due string `json:"due,omitempty" jsonschema:"Due date (RFC 3339)"`
}
type DeleteInput struct {
ID string `json:"id" jsonschema:"Task ID"`
TaskListID string `json:"taskListId" jsonschema:"Task list ID"`
}
type ClearInput struct {
TaskListID string `json:"taskListId" jsonschema:"Task list ID"`
}
// --- Tool Outputs ---
type TaskOutput struct {
ID string `json:"id"`
Title string `json:"title"`
Status string `json:"status,omitempty"`
Due string `json:"due,omitempty"`
Notes string `json:"notes,omitempty"`
Updated string `json:"updated,omitempty"`
Completed string `json:"completed,omitempty"`
}
type TaskListOutput struct {
ID string `json:"id"`
Title string `json:"title"`
Tasks []TaskOutput `json:"tasks"`
}
type SearchOutput struct {
Matches []TaskOutput `json:"matches"`
}
type ListOutput struct {
TaskLists []TaskListOutput `json:"taskLists"`
NextCursor string `json:"nextCursor,omitempty"`
}
type CreateOutput struct {
Task TaskOutput `json:"task"`
}
type UpdateOutput struct {
Task TaskOutput `json:"task"`
}
type DeleteOutput struct {
ID string `json:"id"`
Deleted bool `json:"deleted"`
}
type ClearOutput struct {
TaskListID string `json:"taskListId"`
Cleared bool `json:"cleared"`
}
func registerTools(server *mcp.Server, svc *tasks.Service) {
mcp.AddTool(server, &mcp.Tool{
Name: "search",
Description: "Search for a task in Google Tasks",
Annotations: &mcp.ToolAnnotations{
ReadOnlyHint: true,
DestructiveHint: new(false),
IdempotentHint: true,
OpenWorldHint: new(false),
},
}, searchHandler(svc))
mcp.AddTool(server, &mcp.Tool{
Name: "list",
Description: "List all tasks in Google Tasks",
Annotations: &mcp.ToolAnnotations{
ReadOnlyHint: true,
DestructiveHint: new(false),
IdempotentHint: true,
OpenWorldHint: new(false),
},
}, listHandler(svc))
mcp.AddTool(server, &mcp.Tool{
Name: "create",
Description: "Create a new task in Google Tasks",
Annotations: &mcp.ToolAnnotations{
ReadOnlyHint: false,
DestructiveHint: new(false),
IdempotentHint: false,
OpenWorldHint: new(false),
},
}, createHandler(svc))
mcp.AddTool(server, &mcp.Tool{
Name: "update",
Description: "Update a task in Google Tasks",
Annotations: &mcp.ToolAnnotations{
ReadOnlyHint: false,
DestructiveHint: new(true),
IdempotentHint: true,
OpenWorldHint: new(false),
},
}, updateHandler(svc))
mcp.AddTool(server, &mcp.Tool{
Name: "delete",
Description: "Delete a task in Google Tasks",
Annotations: &mcp.ToolAnnotations{
ReadOnlyHint: false,
DestructiveHint: new(true),
IdempotentHint: true,
OpenWorldHint: new(false),
},
}, deleteHandler(svc))
mcp.AddTool(server, &mcp.Tool{
Name: "clear",
Description: "Clear completed tasks from a Google Tasks task list",
Annotations: &mcp.ToolAnnotations{
ReadOnlyHint: false,
DestructiveHint: new(true),
IdempotentHint: true,
OpenWorldHint: new(false),
},
}, clearHandler(svc))
}
func searchHandler(svc *tasks.Service) func(context.Context, *mcp.CallToolRequest, SearchInput) (*mcp.CallToolResult, SearchOutput, error) {
return func(ctx context.Context, req *mcp.CallToolRequest, input SearchInput) (*mcp.CallToolResult, SearchOutput, error) {
query := strings.ToLower(input.Query)
taskLists, err := svc.Tasklists.List().Context(ctx).Do()
if err != nil {
return nil, SearchOutput{}, fmt.Errorf("list task lists: %w", err)
}
out := SearchOutput{Matches: []TaskOutput{}}
var lines []string
for _, tl := range taskLists.Items {
tasksResp, err := svc.Tasks.List(tl.Id).Context(ctx).Do()
if err != nil {
continue
}
for _, t := range tasksResp.Items {
if strings.Contains(strings.ToLower(t.Title), query) ||
strings.Contains(strings.ToLower(t.Notes), query) {
out.Matches = append(out.Matches, toTaskOutput(t))
lines = append(lines, formatTask(t))
}
}
}
text := "No tasks found matching your search."
if len(lines) > 0 {
text = strings.Join(lines, "\n\n")
}
return textResult(text), out, nil
}
}
func listHandler(svc *tasks.Service) func(context.Context, *mcp.CallToolRequest, ListInput) (*mcp.CallToolResult, ListOutput, error) {
return func(ctx context.Context, req *mcp.CallToolRequest, input ListInput) (*mcp.CallToolResult, ListOutput, error) {
taskLists, err := svc.Tasklists.List().Context(ctx).Do()
if err != nil {
return nil, ListOutput{}, fmt.Errorf("list task lists: %w", err)
}
out := ListOutput{TaskLists: []TaskListOutput{}}
var lines []string
for _, tl := range taskLists.Items {
call := svc.Tasks.List(tl.Id).Context(ctx)
if input.Cursor != "" {
call = call.PageToken(input.Cursor)
}
tasksResp, err := call.Do()
if err != nil {
continue
}
if len(tasksResp.Items) == 0 {
continue
}
tlOut := TaskListOutput{ID: tl.Id, Title: tl.Title, Tasks: []TaskOutput{}}
lines = append(lines, fmt.Sprintf("== Task List: %s ==", tl.Title))
for _, t := range tasksResp.Items {
tlOut.Tasks = append(tlOut.Tasks, toTaskOutput(t))
lines = append(lines, formatTask(t))
}
out.TaskLists = append(out.TaskLists, tlOut)
if tasksResp.NextPageToken != "" && out.NextCursor == "" {
out.NextCursor = tasksResp.NextPageToken
}
}
text := "No tasks found."
if len(lines) > 0 {
text = strings.Join(lines, "\n\n")
}
return textResult(text), out, nil
}
}
func createHandler(svc *tasks.Service) func(context.Context, *mcp.CallToolRequest, CreateInput) (*mcp.CallToolResult, CreateOutput, error) {
return func(ctx context.Context, req *mcp.CallToolRequest, input CreateInput) (*mcp.CallToolResult, CreateOutput, error) {
taskListID := input.TaskListID
if taskListID == "" {
taskListID = "@default"
}
task := &tasks.Task{
Title: input.Title,
Notes: input.Notes,
Due: input.Due,
}
created, err := svc.Tasks.Insert(taskListID, task).Context(ctx).Do()
if err != nil {
return nil, CreateOutput{}, fmt.Errorf("create task: %w", err)
}
return textResult("Task created:\n" + formatTask(created)), CreateOutput{Task: toTaskOutput(created)}, nil
}
}
func updateHandler(svc *tasks.Service) func(context.Context, *mcp.CallToolRequest, UpdateInput) (*mcp.CallToolResult, UpdateOutput, error) {
return func(ctx context.Context, req *mcp.CallToolRequest, input UpdateInput) (*mcp.CallToolResult, UpdateOutput, error) {
taskListID := input.TaskListID
if taskListID == "" {
taskListID = "@default"
}
task := &tasks.Task{}
if input.Title != "" {
task.Title = input.Title
}
if input.Notes != "" {
task.Notes = input.Notes
}
if input.Status != "" {
task.Status = input.Status
}
if input.Due != "" {
task.Due = input.Due
}
updated, err := svc.Tasks.Patch(taskListID, input.ID, task).Context(ctx).Do()
if err != nil {
return nil, UpdateOutput{}, fmt.Errorf("update task: %w", err)
}
return textResult("Task updated:\n" + formatTask(updated)), UpdateOutput{Task: toTaskOutput(updated)}, nil
}
}
func deleteHandler(svc *tasks.Service) func(context.Context, *mcp.CallToolRequest, DeleteInput) (*mcp.CallToolResult, DeleteOutput, error) {
return func(ctx context.Context, req *mcp.CallToolRequest, input DeleteInput) (*mcp.CallToolResult, DeleteOutput, error) {
err := svc.Tasks.Delete(input.TaskListID, input.ID).Context(ctx).Do()
if err != nil {
return nil, DeleteOutput{}, fmt.Errorf("delete task: %w", err)
}
return textResult(fmt.Sprintf("Task %s deleted.", input.ID)), DeleteOutput{ID: input.ID, Deleted: true}, nil
}
}
func clearHandler(svc *tasks.Service) func(context.Context, *mcp.CallToolRequest, ClearInput) (*mcp.CallToolResult, ClearOutput, error) {
return func(ctx context.Context, req *mcp.CallToolRequest, input ClearInput) (*mcp.CallToolResult, ClearOutput, error) {
err := svc.Tasks.Clear(input.TaskListID).Context(ctx).Do()
if err != nil {
return nil, ClearOutput{}, fmt.Errorf("clear tasks: %w", err)
}
return textResult(fmt.Sprintf("Completed tasks cleared from list %s.", input.TaskListID)), ClearOutput{TaskListID: input.TaskListID, Cleared: true}, nil
}
}
// --- Resources ---
func registerResources(server *mcp.Server, svc *tasks.Service) {
server.AddResourceTemplate(
&mcp.ResourceTemplate{
URITemplate: "gtasks:///{taskId}",
Name: "Google Task",
MIMEType: "text/plain",
},
readResourceHandler(svc),
)
}
func readResourceHandler(svc *tasks.Service) func(context.Context, *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
return func(ctx context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
taskID := strings.TrimPrefix(req.Params.URI, "gtasks:///")
taskLists, err := svc.Tasklists.List().Context(ctx).Do()
if err != nil {
return nil, fmt.Errorf("list task lists: %w", err)
}
for _, tl := range taskLists.Items {
t, err := svc.Tasks.Get(tl.Id, taskID).Context(ctx).Do()
if err != nil {
continue
}
details := formatTaskDetails(t)
return &mcp.ReadResourceResult{
Contents: []*mcp.ResourceContents{
{URI: req.Params.URI, Text: details, MIMEType: "text/plain"},
},
}, nil
}
return nil, fmt.Errorf("task %s not found", taskID)
}
}
// --- Helpers ---
func textResult(text string) *mcp.CallToolResult {
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: text},
},
}
}
func toTaskOutput(t *tasks.Task) TaskOutput {
out := TaskOutput{
ID: t.Id,
Title: t.Title,
Status: t.Status,
Due: t.Due,
Notes: t.Notes,
Updated: t.Updated,
}
if t.Completed != nil {
out.Completed = *t.Completed
}
return out
}
func formatTask(t *tasks.Task) string {
completed := "N/A"
if t.Completed != nil && *t.Completed != "" {
completed = *t.Completed
}
due := "Not set"
if t.Due != "" {
due = t.Due
}
notes := "No notes"
if t.Notes != "" {
notes = t.Notes
}
status := "Unknown"
if t.Status != "" {
status = t.Status
}
updated := "Unknown"
if t.Updated != "" {
updated = t.Updated
}
return fmt.Sprintf("Title: %s\n ID: %s\n Status: %s\n Due: %s\n Notes: %s\n Updated: %s\n Completed: %s",
t.Title, t.Id, status, due, notes, updated, completed)
}
func formatTaskDetails(t *tasks.Task) string {
ptrVal := func(s *string, fallback string) string {
if s != nil && *s != "" {
return *s
}
return fallback
}
val := func(s string, fallback string) string {
if s != "" {
return s
}
return fallback
}
return strings.Join([]string{
"Title: " + val(t.Title, "No title"),
"Status: " + val(t.Status, "Unknown"),
"Due: " + val(t.Due, "Not set"),
"Notes: " + val(t.Notes, "No notes"),
fmt.Sprintf("Hidden: %v", t.Hidden),
"Parent: " + val(t.Parent, "Unknown"),
fmt.Sprintf("Deleted: %v", t.Deleted),
"Completed: " + ptrVal(t.Completed, "Unknown"),
"Position: " + val(t.Position, "Unknown"),
"ETag: " + val(t.Etag, "Unknown"),
"Kind: " + val(t.Kind, "Unknown"),
"Created: " + val(t.Updated, "Unknown"),
"Updated: " + val(t.Updated, "Unknown"),
}, "\n")
}