Skip to content

Commit b24c4e5

Browse files
committed
Copy bundle-specific Codex and Claude Code MCP setup
1 parent 24ad2c4 commit b24c4e5

6 files changed

Lines changed: 135 additions & 1 deletion

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import CryptoKit
2+
import Foundation
3+
4+
/// Format local stdio setup without reading, creating or modifying any client config.
5+
struct AgentMCPConfiguration {
6+
let command: String
7+
let serverName: String
8+
9+
static func bundled(in bundle: Bundle = .main, fileManager: FileManager = .default) -> Self? {
10+
let helper = bundle.bundleURL.appendingPathComponent("Contents/Helpers/CodebasicAgentMCP")
11+
guard let values = try? helper.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]),
12+
values.isRegularFile == true, values.isSymbolicLink != true,
13+
fileManager.isExecutableFile(atPath: helper.path),
14+
let identifier = bundle.bundleIdentifier else { return nil }
15+
return Self(command: helper.path, bundleID: identifier)
16+
}
17+
18+
init?(command: String, bundleID: String) {
19+
guard command.hasPrefix("/"), !command.utf8.contains(0), !bundleID.isEmpty else { return nil }
20+
self.command = command
21+
if bundleID == "com.seongjoo.SelectedTextTTS" {
22+
serverName = "codebasic_tts_agent"
23+
} else {
24+
// Every review bundle gets a different key from production and other previews.
25+
let digest = SHA256.hash(data: Data(bundleID.utf8)).prefix(6)
26+
serverName = "codebasic_tts_preview_" + digest.map { String(format: "%02x", $0) }.joined()
27+
}
28+
}
29+
30+
var codexTOML: String {
31+
let quoted = command.unicodeScalars.map { scalar -> String in
32+
switch scalar.value {
33+
case 0x22: return "\\\""
34+
case 0x5c: return "\\\\"
35+
case 0x00...0x1f, 0x7f: return String(format: "\\u%04X", scalar.value)
36+
default: return String(scalar)
37+
}
38+
}.joined()
39+
return "[mcp_servers.\(serverName)]\ncommand = \"\(quoted)\"\n"
40+
}
41+
42+
var claudeCodeCommand: String? {
43+
guard let json = try? JSONSerialization.data(
44+
withJSONObject: ["type": "stdio", "command": command, "args": []],
45+
options: [.sortedKeys, .withoutEscapingSlashes]),
46+
let entry = String(data: json, encoding: .utf8) else { return nil }
47+
let quoted = "'" + entry.replacingOccurrences(of: "'", with: "'\\''") + "'"
48+
return "claude mcp add-json \(serverName) \(quoted) --scope user"
49+
}
50+
}

‎Sources/UI/ExplainWorkspace.swift‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ struct ExplainWorkspace: View {
2121
@State private var pendingReplacement: String?
2222
@State private var confirmEditorChange = false
2323
@State private var copiedRevision: String?
24+
@State private var copiedMCPClient: String?
2425

2526
private var selectedSnapshot: AgentInstructionSnapshot? { app.agentSnapshot(profile) }
2627
private var canUsePlayer: Bool { !app.isBusy && !app.explaining && !app.normalizing }
@@ -198,6 +199,7 @@ struct ExplainWorkspace: View {
198199
Text("MCP 조회 허용 안 함").font(.caption).foregroundStyle(.secondary)
199200
}
200201
if !access.status.isEmpty { Text(access.status).font(.caption).foregroundStyle(.secondary) }
202+
mcpSetup
201203
if let snapshot = selectedSnapshot {
202204
if !snapshot.shareable {
203205
Text("이 지시는 공유 한도(UTF-8 8KB)를 초과했거나 유효하지 않습니다. 원문은 그대로 보존됩니다.")
@@ -221,6 +223,41 @@ struct ExplainWorkspace: View {
221223
}
222224
}
223225

226+
private var mcpSetup: some View {
227+
VStack(alignment: .leading, spacing: 5) {
228+
if let setup = AgentMCPConfiguration.bundled() {
229+
HStack {
230+
Menu("MCP 설정 복사") {
231+
Button("Codex · config.toml") {
232+
copyMCP(setup.codexTOML, client: "Codex")
233+
}
234+
if let command = setup.claudeCodeCommand {
235+
Button("Claude Code · 터미널 등록 명령") {
236+
copyMCP(command, client: "Claude Code")
237+
}
238+
}
239+
}
240+
.accessibilityLabel("MCP 설정 복사")
241+
.accessibilityHint("같은 Mac에 있는 Codex 또는 Claude Code용 설정을 클립보드에 복사합니다.")
242+
if let copiedMCPClient {
243+
Text("\(copiedMCPClient) 설정 복사됨").font(.caption).foregroundStyle(.secondary)
244+
}
245+
}
246+
Text("같은 Mac에서만 사용합니다. Codex는 config.toml에 붙여넣고, Claude Code는 터미널에서 직접 실행하세요. 앱이 다른 위치로 이동하면 설정을 다시 복사하세요.")
247+
.font(.caption).foregroundStyle(.secondary)
248+
} else {
249+
Text("앱에 실행 가능한 MCP 도우미가 없어 설정을 복사할 수 없습니다.")
250+
.font(.caption).foregroundStyle(.secondary)
251+
}
252+
}
253+
}
254+
255+
private func copyMCP(_ text: String, client: String) {
256+
let clipboard = NSPasteboard.general
257+
clipboard.clearContents()
258+
if clipboard.setString(text, forType: .string) { copiedMCPClient = client }
259+
}
260+
224261
private func title(_ selector: String) -> String {
225262
if let builtIn = LocalInstructionProfile.Name(rawValue: selector) { return name(builtIn) }
226263
return catalog.record(selector)?.label ?? selector
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import Foundation
2+
3+
@main struct AgentMCPConfigurationTests {
4+
static func main() throws {
5+
let productionID = "com.seongjoo.SelectedTextTTS"
6+
let path = "/Applications/예시 앱 \"따옴표\" O'Brian \\ 빌드.app/Contents/Helpers/CodebasicAgentMCP"
7+
let config = AgentMCPConfiguration(command: path, bundleID: productionID)!
8+
precondition(config.serverName == "codebasic_tts_agent")
9+
let review = AgentMCPConfiguration(command: path, bundleID: "test.preview")!
10+
precondition(review.serverName.hasPrefix("codebasic_tts_preview_") && review.serverName != config.serverName)
11+
precondition(review.serverName != AgentMCPConfiguration(command: path, bundleID: "test.preview2")!.serverName)
12+
precondition(AgentMCPConfiguration(command: "relative", bundleID: productionID) == nil)
13+
precondition(AgentMCPConfiguration(command: "/invalid\0path", bundleID: productionID) == nil)
14+
precondition(config.codexTOML.contains("O'Brian"))
15+
precondition(config.claudeCodeCommand!.contains("O'\\''Brian"))
16+
precondition(AgentMCPConfiguration.bundled(in: .main) == nil)
17+
18+
let tested: AgentMCPConfiguration
19+
if CommandLine.arguments.count == 2 {
20+
guard let bundle = Bundle(path: CommandLine.arguments[1]),
21+
let bundled = AgentMCPConfiguration.bundled(in: bundle) else {
22+
throw CocoaError(.fileNoSuchFile)
23+
}
24+
precondition(bundled.command == bundle.bundleURL.appendingPathComponent("Contents/Helpers/CodebasicAgentMCP").path)
25+
tested = bundled
26+
} else { tested = config }
27+
let result = ["toml": tested.codexTOML, "shell": tested.claudeCodeCommand!,
28+
"name": tested.serverName, "path": tested.command]
29+
print(String(decoding: try JSONSerialization.data(withJSONObject: result), as: UTF8.self))
30+
}
31+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
"""Parse actual Swift output without running a command or touching client configs (Python 3.11+)."""
2+
import json
3+
import shlex
4+
import sys
5+
import tomllib
6+
7+
result = json.load(sys.stdin)
8+
shell_args = shlex.split(result["shell"])
9+
assert shell_args[:4] == ["claude", "mcp", "add-json", result["name"]]
10+
assert shell_args[5:] == ["--scope", "user"]
11+
assert json.loads(shell_args[4]) == {"command": result["path"], "type": "stdio", "args": []}
12+
assert tomllib.loads(result["toml"]) == {"mcp_servers": {result["name"]: {"command": result["path"]}}}
13+
print("Codex TOML and Claude Code CLI/JSON round trip: exact path, selector and stdio-only payload")

‎build.sh‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,9 @@ case "${1:-install}" in
144144
swiftc -O "$HERE/Sources/Core/AgentCatalog.swift" "$HERE/Sources/Core/AgentDeliveryProofs.swift" \
145145
"$HERE/Sources/Core/ExplanationDraftWorkspace.swift" "$HERE/Tests/AgentCatalogTests.swift" -o "$BUILD_DIR/agent-catalog-tests"
146146
"$BUILD_DIR/agent-catalog-tests" "$catalog_fixture"
147+
swiftc -O "$HERE/Sources/Core/AgentMCPConfiguration.swift" "$HERE/Tests/AgentMCPConfigurationTests.swift" \
148+
-o "$BUILD_DIR/agent-mcp-configuration-tests"
149+
"$BUILD_DIR/agent-mcp-configuration-tests" > "$BUILD_DIR/agent-mcp-configuration-sample.json"
147150
socket_fixture="$(mktemp -d "$BUILD_DIR/socket-test.XXXXXX")"
148151
swiftc -O "$HERE/Sources/App/LocalInstructionSocket.swift" \
149152
"$HERE/Tests/LocalApprovedSocketLifecycleTests.swift" -o "$BUILD_DIR/local-approved-socket-tests"

‎docs/mcp-explanation-drafts.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
command = "/absolute/path/to/Codebasic TTS.app/Contents/Helpers/CodebasicAgentMCP"
1818
```
1919

20-
다른 stdio MCP 클라이언트에도 같은 절대 경로를 실행 명령으로 지정하면 됩니다. 앱을 옮기거나 이름을 바꾸면 이 명령 경로만 수정하세요. 전역 에이전트 설정은 앱이 변경하지 않습니다.
20+
앱의 **MCP 설정 복사** 메뉴로 현재 번들 경로가 포함된 Codex 설정이나 Claude Code 사용자 범위 등록 명령을 복사할 수 있습니다. 복사만으로 설정 파일을 바꾸거나 명령을 실행하지 않습니다. 다른 stdio MCP 클라이언트에도 같은 절대 경로를 실행 명령으로 지정하면 됩니다. 앱을 옮기거나 이름을 바꾸면 이 명령 경로만 수정하세요. 전역 에이전트 설정은 앱이 변경하지 않습니다.
2121

2222
- `tts_agent_status`: 앱 연결과 두 권한의 상태를 확인합니다. 지시나 대본은 읽지 않습니다.
2323
- `get_tts_instructions`: 인자 없이 호출하면 앱이 승인한 선택을 읽습니다. 정확한 `profile` ID를 지정하는 기존 호출도 지원합니다. 기존 기본 ID는 `explain`, `continue`, `normalize`입니다. 답변의 `revision`과 `body_sha256`은 정확한 버전과 UTF-8 원문을 식별합니다. 수신 증명은 도우미 내부에서만 관리됩니다.

0 commit comments

Comments
 (0)