-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp.go
More file actions
601 lines (539 loc) · 20.5 KB
/
Copy pathmcp.go
File metadata and controls
601 lines (539 loc) · 20.5 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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
const (
mcpProtocolVersion = "2025-06-18"
mcpServerInstructions = "Provides secretless opub project and local work-session context. When this MCP server is available, call identify_project at the start of repository work before making funded-work, project, compute-key, or linked-session claims. An opub funded work session begins when the user launches the agent with opub run <agent>; link.linked=true means MCP found a recent unfinished local session for this repo and agent and verified the runtime launch proof inherited from that opub run process. The freshness window is a stale-evidence fallback, not the intended session duration or proof that the agent process is still running. link.linked=false means project configuration exists but no verified active funded-session evidence is present; ask the user to launch with opub run <agent> before describing new funded work as linked. MCP never exposes provider secrets and does not prove provider spend, prompt, response, file, commit, PR, issue, or task matching. Use MCP only for project/session context, and call finish_work_session only when the requested work is genuinely complete."
)
type secretlessState struct {
paths *RepoPaths
config *LocalConfig
session *LocalSession
git gitState
}
type gitState struct {
branch *string
commit *string
originURL *string
}
func loadSecretlessState(repoRoot, target string) (*secretlessState, error) {
var paths *RepoPaths
var err error
if repoRoot != "" {
paths, err = repoPathsFromRootConfigured(repoRoot, target)
} else {
paths, err = discoverRepoPathsConfigured(target)
}
if err != nil {
return nil, err
}
if _, err := os.Stat(paths.Root + "/.git"); err != nil {
return nil, fmt.Errorf("repo root does not contain .git: %s", paths.Root)
}
if repoRoot != "" {
canonical, err := evalSymlinks(repoRoot)
if err == nil {
actual, err2 := evalSymlinks(paths.Root)
if err2 == nil && canonical != actual {
return nil, fmt.Errorf("expected repo root %q does not match active repo root %q", canonical, actual)
}
}
}
cfg, err := readConfig(paths)
if err != nil {
return nil, err
}
var sess *LocalSession
s, err := readSession(paths)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
} else if err == nil {
sess = s
}
gs, err := readGitState(paths)
if err != nil {
return nil, err
}
if err := validateMCPState(paths, cfg, sess, gs); err != nil {
return nil, err
}
return &secretlessState{
paths: paths,
config: cfg,
session: sess,
git: gs,
}, nil
}
func evalSymlinks(p string) (string, error) { return filepath.EvalSymlinks(p) }
func validateMCPState(paths *RepoPaths, cfg *LocalConfig, sess *LocalSession, gs gitState) error {
if cfg.Version != 1 {
return fmt.Errorf("unsupported opub config version %q", cfg.Version)
}
if gs.originURL == nil {
return errors.New("could not verify opub project: git origin is not configured")
}
origin := parseGithubRemoteProject(*gs.originURL)
if origin == "" {
return fmt.Errorf("could not verify opub project against git origin %q", *gs.originURL)
}
if cfg.Project.FullName != origin {
return fmt.Errorf("opub config project %q does not match git origin %q", cfg.Project.FullName, origin)
}
if sess != nil {
if sess.Version != 1 {
return fmt.Errorf("unsupported opub session version %q", sess.Version)
}
if cfg.Project.FullName != sess.ProjectFullName {
return fmt.Errorf("opub config project %q does not match session project %q", cfg.Project.FullName, sess.ProjectFullName)
}
if cfg.ComputeKey.ID != sess.ComputeKeyID {
return fmt.Errorf("opub config compute key %q does not match session compute key %q", cfg.ComputeKey.ID, sess.ComputeKeyID)
}
if cfg.Target.Name != sess.Target {
return fmt.Errorf("opub config target %q does not match session target %q", cfg.Target.Name, sess.Target)
}
}
return nil
}
func readGitState(paths *RepoPaths) (gitState, error) {
gp, err := gitPaths(paths.Root)
if err != nil {
return gitState{}, err
}
headData, err := os.ReadFile(gp.gitDir + "/HEAD")
if err != nil {
return gitState{}, fmt.Errorf("read HEAD: %w", err)
}
head := strings.TrimSpace(string(headData))
var branch, commit *string
if ref, ok := strings.CutPrefix(head, "ref: refs/heads/"); ok {
b := strings.TrimSpace(ref)
branch = &b
} else if head != "" {
commit = &head
}
origin, _ := readGitOrigin(gp)
var originPtr *string
if origin != "" {
originPtr = &origin
}
return gitState{branch: branch, commit: commit, originURL: originPtr}, nil
}
type jsonrpcMessage struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
}
func runMCPStdio(state *secretlessState, r io.Reader, w io.Writer) error {
scanner := bufio.NewScanner(r)
scanner.Buffer(make([]byte, 1024*1024), 1024*1024)
enc := json.NewEncoder(w)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
var msg jsonrpcMessage
if err := json.Unmarshal([]byte(line), &msg); err != nil {
resp := jsonrpcError(json.RawMessage("null"), -32700, "Parse error", err.Error())
enc.Encode(resp)
continue
}
// Notifications (no id) are silently ignored
if msg.ID == nil {
continue
}
resp := handleMCPMessage(state, msg)
if err := enc.Encode(resp); err != nil {
return fmt.Errorf("write MCP response: %w", err)
}
}
return scanner.Err()
}
func handleMCPMessage(state *secretlessState, msg jsonrpcMessage) map[string]interface{} {
switch msg.Method {
case "initialize":
return jsonrpcResult(msg.ID, map[string]interface{}{
"protocolVersion": mcpProtocolVersion,
"capabilities": map[string]interface{}{
"tools": map[string]interface{}{"listChanged": false},
},
"serverInfo": map[string]interface{}{
"name": "opub",
"title": "opub local context",
"version": version,
},
"instructions": mcpServerInstructions,
})
case "tools/list":
return jsonrpcResult(msg.ID, map[string]interface{}{"tools": toolDefinitions()})
case "tools/call":
return callTool(state, msg)
default:
return jsonrpcError(msg.ID, -32601, "Method not found", msg.Method)
}
}
func callTool(state *secretlessState, msg jsonrpcMessage) map[string]interface{} {
var params struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
if err := json.Unmarshal(msg.Params, ¶ms); err != nil || params.Name == "" {
return jsonrpcError(msg.ID, -32602, "Invalid params", "missing tool name")
}
switch params.Name {
case "identify_project":
return toolResult(msg.ID, identifyProject(state))
case "get_active_work_session":
return toolResult(msg.ID, activeWorkSession(state))
case "get_compute_status":
return toolResult(msg.ID, computeStatus(state))
case "finish_work_session":
result, err := finishWorkSession(state)
if err != nil {
return jsonrpcError(msg.ID, -32603, "Internal error", err.Error())
}
return toolResult(msg.ID, result)
default:
return jsonrpcError(msg.ID, -32602, "Unknown tool", params.Name)
}
}
// --- session state ---
type sessionStateVal struct {
name string
active bool
}
func currentSessionState(state *secretlessState) sessionStateVal {
if state.session == nil {
return sessionStateVal{"missing", false}
}
if state.session.FinishedAtUnix != nil {
return sessionStateVal{"finished", false}
}
now := unixNow()
if now-state.session.UpdatedAtUnix > activeSessionWindowSeconds {
return sessionStateVal{"stale", false}
}
if !runtimeLaunchProofMatches(state.session) {
return sessionStateVal{"unverified", false}
}
return sessionStateVal{"active", true}
}
func runtimeLaunchProofMatches(session *LocalSession) bool {
if session == nil || session.LaunchProofHash == nil || *session.LaunchProofHash == "" {
return false
}
token := os.Getenv("OPUB_SESSION_TOKEN")
if token == "" {
return false
}
return hashLaunchProofToken(token) == *session.LaunchProofHash
}
// --- tool implementations ---
func identifyProject(state *secretlessState) map[string]interface{} {
ss := currentSessionState(state)
return map[string]interface{}{
"project": projectJSON(state),
"compute_key": map[string]interface{}{"id": state.config.ComputeKey.ID},
"provider": providerJSON(state),
"target": map[string]interface{}{"name": state.config.Target.Name},
"repo": repoJSON(state),
"session_state": sessionStateJSON(state, ss),
"workflow_guidance": workflowGuidanceJSON(state, ss),
"evidence": evidenceJSON(state, ss),
"link": linkJSON(state, ss),
}
}
func activeWorkSession(state *secretlessState) map[string]interface{} {
ss := currentSessionState(state)
var id, repoRoot interface{}
var startedAt, updatedAt, finishedAt interface{}
repoRoot = state.paths.Root
if state.session != nil {
id = state.session.ID
repoRoot = state.session.RepoRoot
startedAt = state.session.StartedAtUnix
updatedAt = state.session.UpdatedAtUnix
finishedAt = state.session.FinishedAtUnix
}
return map[string]interface{}{
"id": id,
"repo_root": repoRoot,
"project_full_name": state.config.Project.FullName,
"project_id": state.config.Project.ID,
"compute_key_id": state.config.ComputeKey.ID,
"target": state.config.Target.Name,
"started_at_unix": startedAt,
"updated_at_unix": updatedAt,
"finished_at_unix": finishedAt,
"state": ss.name,
"active": ss.active,
"stale_after_seconds": activeSessionWindowSeconds,
"link": minimalLinkJSON(ss),
}
}
func computeStatus(state *secretlessState) map[string]interface{} {
ss := currentSessionState(state)
var sessionID interface{}
var updatedAt interface{}
var finishedAt interface{}
if state.session != nil {
sessionID = state.session.ID
updatedAt = state.session.UpdatedAtUnix
finishedAt = state.session.FinishedAtUnix
}
finished := finishedAt != nil
return map[string]interface{}{
"project": projectJSON(state),
"compute_key": map[string]interface{}{"id": state.config.ComputeKey.ID},
"provider": map[string]interface{}{"name": state.config.Provider.Name, "key_hash": state.config.Provider.KeyHash},
"session": map[string]interface{}{
"id": sessionID,
"target": state.config.Target.Name,
"updated_at_unix": updatedAt,
"state": ss.name,
"active": ss.active,
"stale_after_seconds": activeSessionWindowSeconds,
},
"finished_at_unix": finishedAt,
"workflow": map[string]interface{}{"finished": finished},
"local_state": map[string]interface{}{
"configured": true,
"session_active": ss.active,
"provider_secret_available_to_mcp": false,
},
"provider_status": map[string]interface{}{
"queried": false,
"reason": "MCP is secretless and does not read provider credentials or query provider state.",
},
"link": minimalLinkJSON(ss),
}
}
func finishWorkSession(state *secretlessState) (map[string]interface{}, error) {
if err := ensureActiveSession(state); err != nil {
return nil, err
}
now := unixNow()
state.session.FinishedAtUnix = &now
state.session.UpdatedAtUnix = now
if err := persistSession(state.paths, state.session); err != nil {
return nil, err
}
ss := currentSessionState(state)
return map[string]interface{}{
"finished": true,
"session": map[string]interface{}{
"id": state.session.ID,
"finished_at_unix": state.session.FinishedAtUnix,
"updated_at_unix": state.session.UpdatedAtUnix,
},
"evidence": evidenceJSON(state, ss),
"link": linkJSON(state, ss),
}, nil
}
func ensureActiveSession(state *secretlessState) error {
ss := currentSessionState(state)
if !ss.active {
return fmt.Errorf("opub work session is %s; start a funded session with `opub run %s`",
ss.name, state.config.Target.Name)
}
return nil
}
// --- JSON helpers ---
func projectJSON(state *secretlessState) map[string]interface{} {
return map[string]interface{}{
"full_name": state.config.Project.FullName,
"id": state.config.Project.ID,
}
}
func providerJSON(state *secretlessState) map[string]interface{} {
return map[string]interface{}{
"name": state.config.Provider.Name,
"key_hash": state.config.Provider.KeyHash,
"credential_storage": state.config.Provider.CredentialStorage,
}
}
func repoJSON(state *secretlessState) map[string]interface{} {
return map[string]interface{}{
"root": state.paths.Root,
"git": map[string]interface{}{
"branch": state.git.branch,
"commit": state.git.commit,
"origin_url": state.git.originURL,
},
}
}
func sessionStateJSON(state *secretlessState, ss sessionStateVal) map[string]interface{} {
return map[string]interface{}{
"state": ss.name,
"active": ss.active,
"stale_after_seconds": activeSessionWindowSeconds,
"stale_after_semantics": "This is a freshness cutoff for local session evidence, not the intended duration of the user's work session.",
"started_by": "opub run " + state.config.Target.Name,
"ended_by": "finish_work_session; stale state only means local evidence is too old for linking",
"runtime_proof": runtimeProofJSON(state),
"note": sessionNote(state, ss),
}
}
func workflowGuidanceJSON(state *secretlessState, ss sessionStateVal) map[string]interface{} {
cmd := "opub run " + state.config.Target.Name
return map[string]interface{}{
"session_start": map[string]interface{}{
"command": cmd,
"meaning": "Running opub run <agent> starts a local funded work session for the configured project, compute key, repository, and agent, and passes a runtime launch proof to the launched process.",
},
"current_state": ss.name,
"should_proceed_as_funded_local_session": ss.active,
"freshness_window_semantics": "The stale cutoff only prevents old local evidence from being treated as current. It does not define the intended session length and does not by itself prove the agent process is linked.",
"required_first_tool": "identify_project",
"during_work": []string{
"Use local MCP context for project and session linking only when link.linked is true.",
"Call get_compute_status or get_active_work_session if session status is unclear.",
"Work normally; opub MCP does not track files, commits, PRs, issues, prompts, responses, or work units.",
},
"end_session": map[string]interface{}{
"tool": "finish_work_session",
"when": "Call only when the requested work is complete and no further tool work is needed.",
},
"caveats": []string{
"MCP is secretless and never exposes provider credentials.",
"MCP does not prove provider spend, prompt, response, request, file, commit, PR, issue, or task matching.",
"Provider telemetry links spend to the compute key for ledger math when the provider identifies that key.",
},
"next_action": workflowNextAction(state, ss),
}
}
func linkJSON(state *secretlessState, ss sessionStateVal) map[string]interface{} {
return map[string]interface{}{
"linked": ss.active,
"runtime_proof": runtimeProofJSON(state),
"note": sessionNote(state, ss),
}
}
func minimalLinkJSON(ss sessionStateVal) map[string]interface{} {
return map[string]interface{}{"linked": ss.active}
}
func evidenceJSON(state *secretlessState, ss sessionStateVal) map[string]interface{} {
return map[string]interface{}{
"repo_verified": true,
"target_verified": true,
"local_config_present": true,
"local_session_present": state.session != nil,
"local_session_linked": ss.active,
"runtime_launch_proof_present": os.Getenv("OPUB_SESSION_TOKEN") != "",
"runtime_launch_proof_hash_present": state.session != nil &&
state.session.LaunchProofHash != nil &&
*state.session.LaunchProofHash != "",
"runtime_launch_proof_matched": runtimeLaunchProofMatches(state.session),
"provider_secret_available_to_mcp": false,
}
}
func runtimeProofJSON(state *secretlessState) map[string]interface{} {
hashPresent := state.session != nil &&
state.session.LaunchProofHash != nil &&
*state.session.LaunchProofHash != ""
return map[string]interface{}{
"required": true,
"token_present": os.Getenv("OPUB_SESSION_TOKEN") != "",
"hash_present": hashPresent,
"matched": runtimeLaunchProofMatches(state.session),
"meaning": "A linked session requires a recent unfinished session.json plus a matching runtime launch proof inherited from opub run.",
}
}
func workflowNextAction(state *secretlessState, ss sessionStateVal) string {
if ss.active {
return "Proceed with the requested work using linked local-session caveats."
}
return fmt.Sprintf("Ask the user to start a funded local session with `opub run %s` before describing new work as linked.", state.config.Target.Name)
}
func sessionNote(state *secretlessState, ss sessionStateVal) string {
target := state.config.Target.Name
switch ss.name {
case "active":
return fmt.Sprintf("Local MCP context verified a recent unfinished `opub run %s` session for this repo and agent using runtime launch proof inherited by this MCP process. Provider telemetry links spend to the compute key for ledger math when the provider identifies that key.", target)
case "unverified":
return fmt.Sprintf("This repository has recent unfinished opub session evidence, but MCP did not receive matching runtime launch proof from `opub run %s`; treat it as configured but not linked.", target)
case "finished":
return fmt.Sprintf("The local opub work session is finished. Start a funded session with `opub run %s` before describing new work as linked.", target)
case "stale":
return fmt.Sprintf("The local opub work-session evidence is stale, so MCP cannot treat it as current for linking. Start a funded session with `opub run %s` before describing new work as linked.", target)
case "missing":
return fmt.Sprintf("This repository is configured for opub, but no active funded work session exists. Start one with `opub run %s`.", target)
default:
return "The local opub work session could not be checked against the system clock."
}
}
// --- JSON-RPC response builders ---
func jsonrpcResult(id json.RawMessage, result interface{}) map[string]interface{} {
return map[string]interface{}{
"jsonrpc": "2.0",
"id": id,
"result": result,
}
}
func jsonrpcError(id json.RawMessage, code int, message, data string) map[string]interface{} {
errObj := map[string]interface{}{
"code": code,
"message": message,
}
if data != "" {
errObj["data"] = data
}
return map[string]interface{}{
"jsonrpc": "2.0",
"id": id,
"error": errObj,
}
}
func toolResult(id json.RawMessage, structured interface{}) map[string]interface{} {
text, _ := json.MarshalIndent(structured, "", " ")
return jsonrpcResult(id, map[string]interface{}{
"content": []interface{}{
map[string]interface{}{"type": "text", "text": string(text)},
},
"structuredContent": structured,
"isError": false,
})
}
func toolDefinitions() []interface{} {
emptySchema := map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{},
"additionalProperties": false,
}
return []interface{}{
map[string]interface{}{
"name": "identify_project",
"title": "Identify opub project",
"description": "Session-start tool. Call before funded-work, project, compute-key, or linked-session claims. Returns configured opub project, compute key, agent, repository, session state, link guidance, and safe git metadata without reading secrets.",
"inputSchema": emptySchema,
},
map[string]interface{}{
"name": "get_compute_status",
"title": "Get compute status",
"description": "Check local donated-compute context and link caveats during work without querying provider secrets or changing ledger state.",
"inputSchema": emptySchema,
},
map[string]interface{}{
"name": "get_active_work_session",
"title": "Get active work session",
"description": "Return local opub work-session timing, status, and link guidance from user state.",
"inputSchema": emptySchema,
},
map[string]interface{}{
"name": "finish_work_session",
"title": "Finish work session",
"description": "Mark the active local opub work session as finished when the requested work is genuinely complete.",
"inputSchema": emptySchema,
},
}
}