-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclaudelaunch.go
More file actions
337 lines (322 loc) · 9.26 KB
/
Copy pathclaudelaunch.go
File metadata and controls
337 lines (322 loc) · 9.26 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
package agenthooks
import (
"archive/zip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
)
// claudeLaunchContext is the subset of Claude's argv that changes its MCP
// inventory. Hooks receive CLAUDE_PID but not the launch arguments themselves.
type claudeLaunchContext struct {
ProjectDir string
// Executable is the claude binary that launched this session, recovered
// from CLAUDE_PID. `claude mcp list` is otherwise resolved off PATH, which
// a desktop- or MDM-launched session frequently does not carry — and a
// failed probe silently costs every MCP call its server identity. Mirrors
// codexLaunchContext.Executable.
Executable string
MCPConfigs []string
ReplayArgs []string
PluginDirs []string
StrictMCP bool
Bare bool
SafeMode bool
}
func currentClaudeLaunchContext(cwd string) claudeLaunchContext {
projectDir := os.Getenv("CLAUDE_PROJECT_DIR")
if projectDir == "" {
projectDir = cwd
}
c := claudeLaunchContext{ProjectDir: projectDir}
pid, err := strconv.Atoi(os.Getenv("CLAUDE_PID"))
if err != nil || pid <= 1 {
return c
}
args, err := procArgs(pid)
if err != nil || len(args) == 0 {
return c
}
c = parseClaudeLaunchArgs(args, projectDir)
// Prefer the kernel's record over argv[0], which a launcher is free to set
// to anything. It is absolute on Linux (/proc/pid/exe) and Windows
// (QueryFullProcessImageName); on macOS it is the exec path, absolute
// whenever the launcher resolved one (as a PATH lookup does). Anything not
// absolute falls back to the PATH search in runClaudeMCPList — no worse
// than resolving off PATH alone, which is all this had before.
if executable, err := procExecutable(pid); err == nil && executable != "" {
c.Executable = executable
}
return c
}
func parseClaudeLaunchArgs(args []string, projectDir string) claudeLaunchContext {
c := claudeLaunchContext{ProjectDir: projectDir}
if len(args) > 0 {
c.Executable = args[0]
}
for i := 1; i < len(args); i++ {
a := args[i]
if a == "--" {
break
}
switch a {
case "--strict-mcp-config":
c.StrictMCP = true
case "--bare":
c.Bare = true
case "--safe-mode":
c.SafeMode = true
case "--mcp-config":
for i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
i++
c.MCPConfigs = append(c.MCPConfigs, args[i])
}
case "--settings", "--setting-sources", "--plugin-dir":
if i+1 >= len(args) {
continue
}
i++
c.addReplayArg(a, args[i])
case "--plugin-url":
// Re-fetching a mutable remote plugin from a hook can execute code
// that the running session never loaded. Leave it unattributed.
i++
default:
name, value, ok := strings.Cut(a, "=")
if !ok {
continue
}
switch name {
case "--mcp-config":
c.MCPConfigs = append(c.MCPConfigs, value)
case "--settings", "--setting-sources", "--plugin-dir":
c.addReplayArg(name, value)
}
}
}
return c
}
func (c *claudeLaunchContext) addReplayArg(name, value string) {
c.ReplayArgs = append(c.ReplayArgs, name, value)
if name == "--plugin-dir" {
c.PluginDirs = append(c.PluginDirs, value)
}
}
func (c claudeLaunchContext) explicitMCPEntries() []mcpConfigEntry {
// Later command-line configs win name collisions.
var groups [][]mcpConfigEntry
for i := len(c.MCPConfigs) - 1; i >= 0; i-- {
if data, ok := c.readValue(c.MCPConfigs[i]); ok {
groups = append(groups, parseClaudeLaunchMCPConfig(data))
}
}
return firstMCPEntries(groups...)
}
func (c claudeLaunchContext) readValue(value string) ([]byte, bool) {
if strings.HasPrefix(strings.TrimSpace(value), "{") {
return []byte(value), true
}
path := value
if !filepath.IsAbs(path) {
path = filepath.Join(c.ProjectDir, path)
}
data, err := os.ReadFile(path)
return data, err == nil
}
// barePluginEntries keeps only servers belonging to explicitly supplied local
// plugins. Claude's management command currently ignores --bare for its normal
// inventory, so the result must be filtered back to the launch-only plugins.
func (c claudeLaunchContext) barePluginEntries(entries []mcpConfigEntry) []mcpConfigEntry {
plugins := make(map[string]bool, len(c.PluginDirs))
for _, dir := range c.PluginDirs {
if name := c.pluginName(dir); name != "" {
plugins[name] = true
}
}
var out []mcpConfigEntry
for _, e := range entries {
if plugins[e.Plugin] {
out = append(out, e)
}
}
return out
}
func (c claudeLaunchContext) pluginName(value string) string {
path := value
if !filepath.IsAbs(path) {
path = filepath.Join(c.ProjectDir, path)
}
if strings.EqualFold(filepath.Ext(path), ".zip") {
zr, err := zip.OpenReader(path)
if err != nil {
return ""
}
defer func() { _ = zr.Close() }()
for _, f := range zr.File {
if strings.HasSuffix(filepath.ToSlash(f.Name), "/.claude-plugin/plugin.json") || f.Name == ".claude-plugin/plugin.json" {
r, err := f.Open()
if err != nil {
return ""
}
data, _ := io.ReadAll(r)
_ = r.Close()
return pluginNameJSON(data)
}
}
return ""
}
data, err := os.ReadFile(filepath.Join(path, ".claude-plugin", "plugin.json"))
if err != nil {
return filepath.Base(path)
}
return pluginNameJSON(data)
}
func pluginNameJSON(data []byte) string {
var manifest struct {
Name string `json:"name"`
}
if json.Unmarshal(data, &manifest) != nil {
return ""
}
return manifest.Name
}
// cacheKey fingerprints launch inputs without persisting argv, inline configs,
// settings, or environment values that may contain credentials.
func (c claudeLaunchContext) cacheKey() string {
h := sha256.New()
writeHashPart := func(s string) {
_, _ = h.Write([]byte(s))
_, _ = h.Write([]byte{0})
}
writeHashPart("agenthooks-claude-mcp-v3")
writeHashPart(c.ProjectDir)
// Two Claude installs can present different inventories from one project
// dir, so the snapshot is only reusable for the binary that produced it.
writeHashPart(c.Executable)
writeHashPart(strconv.FormatBool(c.StrictMCP))
writeHashPart(strconv.FormatBool(c.Bare))
writeHashPart(strconv.FormatBool(c.SafeMode))
for i := 0; i < len(c.ReplayArgs); i++ {
writeHashPart(c.ReplayArgs[i])
if c.ReplayArgs[i] == "--settings" && i+1 < len(c.ReplayArgs) {
value := c.ReplayArgs[i+1]
if data, ok := c.readValue(value); ok {
sum := sha256.Sum256(data)
writeHashPart(hex.EncodeToString(sum[:]))
}
}
if c.ReplayArgs[i] == "--plugin-dir" && i+1 < len(c.ReplayArgs) {
c.hashPluginDir(c.ReplayArgs[i+1], writeHashPart)
}
}
hashLaunchEnvironment(writeHashPart)
return hex.EncodeToString(h.Sum(nil))[:32]
}
func hashLaunchEnvironment(writeHashPart func(string)) {
env := append([]string(nil), os.Environ()...)
sort.Strings(env)
for _, kv := range env {
name, _, _ := strings.Cut(kv, "=")
switch name {
case "CLAUDE_PID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_ENV_FILE", "CODEX_THREAD_ID", "CODEX_TURN_ID", "CODEX_PID", "PWD", "OLDPWD", "SHLVL", "_":
continue
}
writeHashPart(kv)
}
}
func (c claudeLaunchContext) hashPluginDir(value string, writeHashPart func(string)) {
path := value
if !filepath.IsAbs(path) {
path = filepath.Join(c.ProjectDir, path)
}
if strings.EqualFold(filepath.Ext(path), ".zip") {
if info, err := os.Stat(path); err == nil {
writeHashPart(strconv.FormatInt(info.Size(), 10))
writeHashPart(strconv.FormatInt(info.ModTime().UnixNano(), 10))
}
return
}
for _, name := range []string{
filepath.Join(".claude-plugin", "plugin.json"),
".mcp.json",
"plugin.json",
} {
if data, err := os.ReadFile(filepath.Join(path, name)); err == nil {
sum := sha256.Sum256(data)
writeHashPart(name)
writeHashPart(hex.EncodeToString(sum[:]))
}
}
}
func parseClaudeLaunchMCPConfig(data []byte) []mcpConfigEntry {
var doc struct {
MCPServers map[string]mcpServerJSON `json:"mcpServers"`
}
if json.Unmarshal(data, &doc) != nil {
return nil
}
names := make([]string, 0, len(doc.MCPServers))
for name := range doc.MCPServers {
names = append(names, name)
}
sort.Strings(names)
var out []mcpConfigEntry
for _, name := range names {
server := doc.MCPServers[name]
typ := strings.ToLower(server.Type)
if server.URL != "" && typ != "http" && typ != "streamable-http" && typ != "sse" && typ != "ws" {
continue
}
if server.Command != "" && typ != "" && typ != "stdio" {
continue
}
args := make([]string, len(server.Args))
for i, arg := range server.Args {
args[i] = expandClaudeMCPEnv(arg)
}
entry := mcpConfigEntry{
Name: name,
URL: expandClaudeMCPEnv(server.URL),
Command: joinCommand(expandClaudeMCPEnv(server.Command), args),
}
if entry.URL != "" || entry.Command != "" {
out = append(out, entry)
}
}
return out
}
func expandClaudeMCPEnv(value string) string {
var out strings.Builder
for {
start := strings.Index(value, "${")
if start < 0 {
out.WriteString(value)
return out.String()
}
end := strings.IndexByte(value[start+2:], '}')
if end < 0 {
out.WriteString(value)
return out.String()
}
end += start + 2
out.WriteString(value[:start])
expression := value[start+2 : end]
name, fallback, hasFallback := strings.Cut(expression, ":-")
replacement, found := os.LookupEnv(name)
if hasFallback && (!found || replacement == "") {
replacement = fallback
found = true
}
if found {
out.WriteString(replacement)
} else {
out.WriteString(value[start : end+1])
}
value = value[end+1:]
}
}