-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmcplistcache.go
More file actions
298 lines (274 loc) · 8.01 KB
/
Copy pathmcplistcache.go
File metadata and controls
298 lines (274 loc) · 8.01 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
package agenthooks
import (
"context"
"encoding/json"
"os"
"os/exec"
"path/filepath"
"time"
)
const (
mcpListProbeTimeout = 15 * time.Second
mcpListWaitTimeout = mcpListProbeTimeout + time.Second
mcpListRefreshInterval = 5 * time.Minute
mcpListCacheRetention = 24 * time.Hour
)
type mcpListCache struct {
CheckedAt int64 `json:"checked_at"`
Entries []mcpConfigEntry `json:"entries"`
HasSnapshot bool `json:"has_snapshot,omitempty"`
}
func (r *Runner) claudeMCPWarmContext(cwd string) (claudeLaunchContext, bool) {
if r.mcpResolveOff || r.mcpListOff {
return claudeLaunchContext{}, false
}
launch := currentClaudeLaunchContext(cwd)
if launch.SafeMode || launch.StrictMCP || (launch.Bare && len(launch.PluginDirs) == 0) {
return claudeLaunchContext{}, false
}
return launch, true
}
func (r *Runner) shouldWarmClaudeMCP(cwd string) bool {
_, ok := r.claudeMCPWarmContext(cwd)
return ok
}
func (r *Runner) warmClaudeMCP(cwd string) {
if launch, ok := r.claudeMCPWarmContext(cwd); ok {
_ = r.claudeMCPListEntries(launch)
}
}
func (r *Runner) claudeMCPListEntries(launch claudeLaunchContext) []mcpConfigEntry {
entries, _ := r.claudeMCPListSnapshot(context.Background(), launch)
return entries
}
func (r *Runner) claudeMCPListSnapshot(ctx context.Context, launch claudeLaunchContext) ([]mcpConfigEntry, bool) {
return r.cachedMCPListEntries(ctx, launch.cacheKey(), func(ctx context.Context) ([]mcpConfigEntry, bool) {
return runClaudeMCPList(ctx, launch)
})
}
func (r *Runner) cachedMCPListEntries(parent context.Context, key string, probe func(context.Context) ([]mcpConfigEntry, bool)) ([]mcpConfigEntry, bool) {
ctx, cancel := context.WithTimeout(parent, mcpListWaitTimeout)
defer cancel()
dir := r.mcpListCacheDir()
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, false
}
path := filepath.Join(dir, key+".json")
now := r.mcpListNow()
cached := readMCPListCache(path)
if mcpListCacheFresh(cached, now) {
return cached.Entries, cached.HasSnapshot
}
if ctx.Err() != nil {
return cached.Entries, cached.HasSnapshot
}
cleanupMCPListCache(dir, time.Now())
// Only one process runs the expensive health check for a context. Waiters
// consume its replacement snapshot instead of starting a probe stampede.
var unlock func()
backoff := 25 * time.Millisecond
for {
release, ok, lockErr := tryMCPListLock(path + ".lock")
if lockErr != nil {
if cached.CheckedAt != 0 {
return cached.Entries, cached.HasSnapshot
}
if entries, success := probe(ctx); success {
return entries, true
}
return nil, false
}
if ok {
unlock = release
break
}
if latest := readMCPListCache(path); mcpListCacheFresh(latest, r.mcpListNow()) {
return latest.Entries, latest.HasSnapshot
}
select {
case <-ctx.Done():
if latest := readMCPListCache(path); latest.CheckedAt > cached.CheckedAt {
return latest.Entries, latest.HasSnapshot
}
return cached.Entries, cached.HasSnapshot
case <-time.After(backoff):
}
backoff = min(2*backoff, 250*time.Millisecond)
}
defer unlock()
// The waiter may have observed staleness immediately before another
// process refreshed and released the lock.
cached = readMCPListCache(path)
now = r.mcpListNow()
if mcpListCacheFresh(cached, now) {
return cached.Entries, cached.HasSnapshot
}
if ctx.Err() != nil {
return cached.Entries, cached.HasSnapshot
}
if entries, success := probe(ctx); success {
cached.Entries = entries // successful probes replace, so removals stick
cached.HasSnapshot = true
}
if ctx.Err() != nil {
return cached.Entries, cached.HasSnapshot
}
cached.CheckedAt = now.Unix()
writeMCPListCache(path, cached)
return cached.Entries, cached.HasSnapshot
}
func (r *Runner) cachedMCPListSnapshot(key string) ([]mcpConfigEntry, bool) {
cached := readMCPListCache(filepath.Join(r.mcpListCacheDir(), key+".json"))
if !mcpListCacheFresh(cached, r.mcpListNow()) {
return nil, false
}
return cached.Entries, cached.HasSnapshot
}
func (r *Runner) mcpListCacheDir() string {
if r.dedupDir != "" {
return filepath.Join(r.dedupDir, "agenthooks-mcplist")
}
if dir, err := os.UserCacheDir(); err == nil {
return filepath.Join(dir, "agenthooks", "mcp-list")
}
return filepath.Join(os.TempDir(), "agenthooks-mcplist")
}
func (r *Runner) currentCodexLaunchContext(cwd string) (codexLaunchContext, bool) {
if r.codexLaunchContext != nil {
launch := *r.codexLaunchContext
if cwd != "" {
launch.CWD = cwd
}
return launch, true
}
return currentCodexLaunchContext(cwd)
}
func (r *Runner) codexMCPWarmContext(cwd string) (codexLaunchContext, bool) {
if r.mcpResolveOff || r.mcpListOff {
return codexLaunchContext{}, false
}
launch, ok := r.currentCodexLaunchContext(cwd)
if !ok || launch.Unreplayable {
return codexLaunchContext{}, false
}
return launch, true
}
func (r *Runner) warmCodexMCP(launch codexLaunchContext) {
if !r.mcpResolveOff && !r.mcpListOff && !launch.Unreplayable {
_, _ = r.codexMCPListEntries(context.Background(), launch)
}
}
func (r *Runner) codexMCPListEntries(ctx context.Context, launch codexLaunchContext) ([]mcpConfigEntry, bool) {
return r.cachedMCPListEntries(ctx, launch.cacheKey(), func(ctx context.Context) ([]mcpConfigEntry, bool) {
return runCodexMCPList(ctx, launch)
})
}
func cleanupMCPListCache(dir string, now time.Time) {
entries, err := os.ReadDir(dir)
if err != nil {
return
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
if info, err := entry.Info(); err == nil && now.Sub(info.ModTime()) > mcpListCacheRetention {
_ = os.Remove(filepath.Join(dir, entry.Name()))
}
}
}
func (r *Runner) mcpListNow() time.Time { return r.now() }
func readMCPListCache(path string) mcpListCache {
data, err := os.ReadFile(path)
if err != nil {
return mcpListCache{}
}
var cached mcpListCache
if json.Unmarshal(data, &cached) != nil {
return mcpListCache{}
}
return cached
}
func mcpListCacheFresh(cached mcpListCache, now time.Time) bool {
return cached.CheckedAt != 0 && now.Sub(time.Unix(cached.CheckedAt, 0)) < mcpListRefreshInterval
}
func writeMCPListCache(path string, cached mcpListCache) {
data, err := json.Marshal(cached)
if err != nil {
return
}
tmp, err := os.CreateTemp(filepath.Dir(path), "inventory-*")
if err != nil {
return
}
tmpPath := tmp.Name()
if _, err = tmp.Write(data); err == nil {
err = tmp.Close()
} else {
_ = tmp.Close()
}
if err == nil {
err = os.Rename(tmpPath, path)
}
if err != nil {
_ = os.Remove(tmpPath)
}
}
func runClaudeMCPList(parent context.Context, launch claudeLaunchContext) ([]mcpConfigEntry, bool) {
// Prefer the binary that launched this session over a PATH search: hooks
// inherit the session's environment, and a desktop- or MDM-launched
// Claude frequently passes one without the CLI on it. Same order as
// runCodexMCPList.
bin := launch.Executable
if bin == "" {
bin = "claude"
}
if !filepath.IsAbs(bin) {
var err error
bin, err = exec.LookPath(bin)
if err != nil {
return nil, false
}
}
ctx, cancel := context.WithTimeout(parent, mcpListProbeTimeout)
defer cancel()
args := append([]string(nil), launch.ReplayArgs...)
if launch.Bare {
args = append([]string{"--bare"}, args...)
}
args = append(args, "mcp", "list")
cmd := exec.CommandContext(ctx, bin, args...)
if launch.ProjectDir != "" {
cmd.Dir = launch.ProjectDir
}
out, err := cmd.Output()
if err != nil {
return nil, false
}
return parseClaudeMCPList(string(out)), true
}
func runCodexMCPList(parent context.Context, launch codexLaunchContext) ([]mcpConfigEntry, bool) {
bin := launch.Executable
if bin == "" {
bin = "codex"
}
if !filepath.IsAbs(bin) {
var err error
bin, err = exec.LookPath(bin)
if err != nil {
return nil, false
}
}
ctx, cancel := context.WithTimeout(parent, mcpListProbeTimeout)
defer cancel()
args := append(launch.replayArgs(), "mcp", "list", "--json")
cmd := exec.CommandContext(ctx, bin, args...)
if launch.CWD != "" {
cmd.Dir = launch.CWD
}
out, err := cmd.Output()
if err != nil {
return nil, false
}
return decodeCodexMCPList(out)
}