Graphley / app · graphley.ai / Sources / AnalyticsKit / MCPServer.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// STDIO MCP server, run as `<app executable> --mcp` (the Inkspring pattern): it reads and writes the |
| 4 | /// same local store as the app, so an agent can set everything up while the app shows the result. |
| 5 | /// Every write is logged to `Workspace.agentLog` and shown in the app's Agents screen. |
| 6 | public final class MCPServer: @unchecked Sendable { |
| 7 | let store: WorkspaceStore |
| 8 | let environment: [String: String] |
| 9 | var clientName = "Agent" |
| 10 | let refresh: @Sendable () async -> Refresher.Report |
| 11 | let discover: @Sendable () async throws -> [GoogleAnalytics.Property] |
| 12 | |
| 13 | public init(store: WorkspaceStore, |
| 14 | environment: [String: String] = ProcessInfo.processInfo.environment, |
| 15 | refresh: (@Sendable () async -> Refresher.Report)? = nil, |
| 16 | discover: (@Sendable () async throws -> [GoogleAnalytics.Property])? = nil) { |
| 17 | self.store = store |
| 18 | self.environment = environment |
| 19 | self.refresh = refresh ?? { await Refresher(store: store, cloud: SnapshotSync()).refreshAll() } |
| 20 | self.discover = discover ?? { try await GoogleAnalytics().properties() } |
| 21 | } |
| 22 | |
| 23 | struct Tool { |
| 24 | let name: String, summary: String |
| 25 | var fields: [String: [String: Any]] = [:] |
| 26 | var required: [String] = [] |
| 27 | var writes = false, network = false, credentials = false |
| 28 | var json: [String: Any] { |
| 29 | ["name": name, "description": summary, |
| 30 | "inputSchema": ["type": "object", "properties": fields, "required": required, "additionalProperties": false], |
| 31 | "annotations": ["readOnlyHint": !writes, "destructiveHint": false, "openWorldHint": network]] |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | // JSON schema fragments. Computed because `[String: Any]` isn't Sendable and can't be a shared static. |
| 36 | static var str: [String: Any] { ["type": "string"] } |
| 37 | static var int: [String: Any] { ["type": "integer", "minimum": 1, "maximum": 400] } |
| 38 | static var strs: [String: Any] { ["type": "array", "items": ["type": "string"]] } |
| 39 | static var metric: [String: Any] { ["type": "string", "enum": Metric.allCases.map(\.rawValue)] } |
| 40 | static var kind: [String: Any] { ["type": "string", "enum": Widget.Kind.allCases.map(\.rawValue)] } |
| 41 | |
| 42 | static var tools: [Tool] { [ |
| 43 | .init(name: "get_status", summary: "Which accounts are connected, how many sites, apps and dashboards exist, and when data was last refreshed. Call this first."), |
| 44 | .init(name: "list_sites", summary: "List tracked websites with their IDs and GA4 property IDs."), |
| 45 | .init(name: "list_apps", summary: "List tracked App Store apps."), |
| 46 | .init(name: "list_dashboards", summary: "List dashboards and their widgets."), |
| 47 | .init(name: "query_metric", summary: "Daily values for a metric. Omit site_ids for all sites. breakdown can be 'page' or 'platform'.", |
| 48 | fields: ["metric": metric, "site_ids": strs, "days": int, "breakdown": str, "event": str], required: ["metric"]), |
| 49 | .init(name: "compare_periods", summary: "Total for the last N days vs the N days before, per site, with percent change.", |
| 50 | fields: ["metric": metric, "site_ids": strs, "days": int], required: ["metric"]), |
| 51 | .init(name: "discover_ga4_properties", summary: "Find every GA4 property the signed-in Google account can read, marked with whether it is already tracked.", network: true), |
| 52 | .init(name: "add_site", summary: "Track a website. Use the property ID from discover_ga4_properties.", |
| 53 | fields: ["name": str, "ga4_property_id": str, "url": str], required: ["name", "ga4_property_id"], writes: true), |
| 54 | .init(name: "update_site", summary: "Rename a site or change its GA4 property or URL.", |
| 55 | fields: ["site_id": str, "name": str, "ga4_property_id": str, "url": str], required: ["site_id"], writes: true), |
| 56 | .init(name: "archive_site", summary: "Stop tracking a site. Its history is kept and it can be restored.", |
| 57 | fields: ["site_id": str], required: ["site_id"], writes: true), |
| 58 | .init(name: "add_app", summary: "Track an App Store app by its Apple ID, optionally linked to its website.", |
| 59 | fields: ["apple_id": str, "name": str, "site_id": str], required: ["apple_id", "name"], writes: true), |
| 60 | .init(name: "create_dashboard", summary: "Create an empty dashboard.", fields: ["name": str], required: ["name"], writes: true), |
| 61 | .init(name: "add_widget", summary: "Add a chart or number to a dashboard.", |
| 62 | fields: ["dashboard_id": str, "title": str, "kind": kind, "metric": metric, "site_ids": strs, "days": int, "breakdown": str, "event": str], |
| 63 | required: ["dashboard_id", "title", "kind", "metric"], writes: true), |
| 64 | .init(name: "remove_widget", summary: "Remove a widget from a dashboard.", fields: ["dashboard_id": str, "widget_id": str], required: ["dashboard_id", "widget_id"], writes: true), |
| 65 | .init(name: "refresh_all", summary: "Pull fresh numbers from Google Analytics and App Store Connect now, then sync to iPhone.", writes: true, network: true), |
| 66 | .init(name: "set_app_store_key", summary: "Save an App Store Connect API key to the Keychain. The private key is read from the GRAPHLEY_ASC_PRIVATE_KEY environment variable of this MCP process, never from tool arguments. Requires 'Let agents set keys' in Settings.", |
| 67 | fields: ["key_id": str, "issuer_id": str, "vendor_number": str, "replace_existing": ["type": "boolean"]], |
| 68 | required: ["key_id", "issuer_id", "vendor_number"], writes: true, credentials: true), |
| 69 | .init(name: "setup_portfolio", summary: "Add or update every portfolio site (with its section sites), app, follower account, ad campaign (all Expired), caveat note and the nine portfolio dashboards. Safe to run again: it only fills in and corrects.", writes: true), |
| 70 | .init(name: "import_history", summary: "Import history rows from the old pull. kind: followers {account, day, count}; videos {video_id, account, title, kind, published, url, day, views, likes}; ads {campaign_id, day, cost, clicks, impressions, conversions}; ratings {apple_id, day, avg, count, by_country}; reviews {review_id, apple_id, app, country, stars, title, text, version, author, date, first_seen, url}. Existing rows for the same day are replaced.", |
| 71 | fields: ["kind": ["type": "string", "enum": ["followers", "videos", "ads", "ratings", "reviews"]], "rows": ["type": "array", "items": ["type": "object"]], |
| 72 | "mark_reviews_sent": ["type": "boolean"]], |
| 73 | required: ["kind", "rows"], writes: true), |
| 74 | .init(name: "record_followers", summary: "Record today's (or a given day's) follower count for an account without an API (Substack, LinkedIn).", |
| 75 | fields: ["account_id": str, "count": ["type": "integer", "minimum": 0], "day": str], required: ["account_id", "count"], writes: true), |
| 76 | .init(name: "export_backup", summary: "The whole workspace (sites, apps, dashboards, accounts, reviews, campaigns, notes) and every stored data point as one JSON object, for a backup or a copy. Keys are never included: they stay in the Keychain."), |
| 77 | .init(name: "list_reviews", summary: "Written App Store reviews with the day each was first seen, and the review to-dos waiting for OpenTalon."), |
| 78 | .init(name: "set_source_key", summary: "Save a key for a data source to the Keychain: bing (Bing Webmaster API key), x (X API bearer token), instagram (Graph API token), opentalon (the JSON with port and token of OpenTalon's local MCP server). The value is read from the GRAPHLEY_SOURCE_KEY environment variable of this MCP process, never from tool arguments. Requires 'Let agents set keys' in Settings.", |
| 79 | fields: ["source": ["type": "string", "enum": ["bing", "x", "instagram", "opentalon"]], "replace_existing": ["type": "boolean"]], |
| 80 | required: ["source"], writes: true, credentials: true), |
| 81 | .init(name: "set_google_service_account", summary: "Save a Google service account key for Google Analytics, used instead of signing in. The key JSON is read from the GRAPHLEY_GOOGLE_SERVICE_ACCOUNT environment variable of this MCP process, never from tool arguments. The service account needs Viewer access in GA4. Requires 'Let agents set keys' in Settings.", |
| 82 | fields: ["replace_existing": ["type": "boolean"]], writes: true, credentials: true) |
| 83 | ] } |
| 84 | |
| 85 | // MARK: Transport |
| 86 | |
| 87 | public func run() async { |
| 88 | let input = FileHandle.standardInput, output = FileHandle.standardOutput |
| 89 | var line = Data() |
| 90 | while true { |
| 91 | let chunk = input.availableData |
| 92 | if chunk.isEmpty { if !line.isEmpty { await respond(line, output) }; return } |
| 93 | for byte in chunk { |
| 94 | if byte == 10 { if !line.isEmpty { await respond(line, output) }; line.removeAll(keepingCapacity: true) } |
| 95 | else if line.count < 1_048_576 { line.append(byte) } |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | private func respond(_ data: Data, _ output: FileHandle) async { |
| 101 | let reply: [String: Any]? |
| 102 | if let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] { reply = await handle(request) } |
| 103 | else { reply = failure(NSNull(), -32700, "Parse error.") } |
| 104 | if let reply, var json = try? JSONSerialization.data(withJSONObject: reply) { json.append(10); try? output.write(contentsOf: json) } |
| 105 | } |
| 106 | |
| 107 | public func handle(_ request: [String: Any]) async -> [String: Any]? { |
| 108 | let id = request["id"] ?? NSNull() |
| 109 | guard let method = request["method"] as? String else { return failure(id, -32600, "Invalid request.") } |
| 110 | guard request["id"] != nil else { return nil } // notification |
| 111 | let params = request["params"] as? [String: Any] ?? [:] |
| 112 | switch method { |
| 113 | case "initialize": |
| 114 | if let info = params["clientInfo"] as? [String: Any], let name = info["name"] as? String { clientName = name } |
| 115 | let supported = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"] |
| 116 | let asked = params["protocolVersion"] as? String ?? "" |
| 117 | return success(id, ["protocolVersion": supported.contains(asked) ? asked : supported[0], |
| 118 | "capabilities": ["tools": ["listChanged": false]], |
| 119 | "serverInfo": ["name": "graphley", "version": "0.1.10"], |
| 120 | "instructions": "Call get_status first. To set up tracking: discover_ga4_properties, then add_site for each property the user wants. Ask before archiving sites. Never ask the user to paste keys into chat."]) |
| 121 | case "ping": return success(id, [:]) |
| 122 | case "tools/list": return success(id, ["tools": Self.tools.map(\.json)]) |
| 123 | case "tools/call": |
| 124 | let name = params["name"] as? String ?? "" |
| 125 | let args = params["arguments"] as? [String: Any] ?? [:] |
| 126 | do { |
| 127 | let result = try await call(name, args) |
| 128 | let text = String(decoding: try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]), as: UTF8.self) |
| 129 | return success(id, ["content": [["type": "text", "text": text]], "structuredContent": result]) |
| 130 | } catch { |
| 131 | return success(id, ["content": [["type": "text", "text": error.localizedDescription]], "isError": true]) |
| 132 | } |
| 133 | default: return failure(id, -32601, "Unknown method \(method).") |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // MARK: Tools |
| 138 | |
| 139 | func call(_ name: String, _ a: [String: Any]) async throws -> [String: Any] { |
| 140 | guard let tool = Self.tools.first(where: { $0.name == name }) else { throw AnalyticsError.missing("Unknown tool \(name).") } |
| 141 | let ws = try store.load() |
| 142 | if tool.writes && !ws.settings.agentsCanWrite { throw AnalyticsError.notAllowed("Turn on “Let agents make changes” in Settings → Agents.") } |
| 143 | if tool.credentials && !ws.settings.agentsCanSetKeys { throw AnalyticsError.notAllowed("Turn on “Let agents set keys” in Settings → Agents.") } |
| 144 | func s(_ k: String) -> String? { (a[k] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty } |
| 145 | func need(_ k: String) throws -> String { guard let v = s(k) else { throw AnalyticsError.missing("\(k) is required.") }; return v } |
| 146 | let days = a["days"] as? Int ?? 30 |
| 147 | |
| 148 | switch name { |
| 149 | case "get_status": |
| 150 | let pts = try store.points() |
| 151 | return ["sites": ws.sites.filter { !$0.archived }.count, "apps": ws.apps.count, "dashboards": ws.dashboards.count, |
| 152 | "latest_day": orNull(pts.map(\.day).max()), |
| 153 | "last_refresh_at": orNull(ws.settings.lastRefreshAt?.ISO8601Format()), |
| 154 | "share_with_iphone": ws.settings.shareWithIPhone, "last_shared_at": orNull(ws.settings.lastSharedAt?.ISO8601Format()), |
| 155 | "google_signed_in": GoogleAuth.isConfigured, "google_service_account": Keychain.has(.googleServiceAccount), "app_store_connect_key": AppStoreConnect().isConfigured, |
| 156 | "bing_key": BingWebmaster.isConfigured, "x_token": Keychain.has(.xBearerToken), "instagram_token": Keychain.has(.instagramToken), |
| 157 | "opentalon_connection": OpenTalonTodos.isConfigured, "socials": ws.socials.count, "reviews": (ws.reviews ?? []).count, |
| 158 | "campaigns": (ws.campaigns ?? []).count, |
| 159 | "agents_can_write": ws.settings.agentsCanWrite, "agents_can_set_keys": ws.settings.agentsCanSetKeys] |
| 160 | case "list_sites": |
| 161 | return ["sites": ws.sites.map { ["id": $0.id, "name": $0.name, "ga4_property_id": orNull($0.ga4PropertyID), "url": orNull($0.url?.absoluteString), "archived": $0.archived] }] |
| 162 | case "list_apps": |
| 163 | return ["apps": ws.apps.map { ["apple_id": $0.id, "name": $0.name, "site_id": orNull($0.siteID)] }] |
| 164 | case "list_dashboards": |
| 165 | return ["dashboards": try JSONSerialization.jsonObject(with: JSONEncoder.analytics.encode(ws.dashboards))] |
| 166 | case "query_metric": |
| 167 | guard let metric = Metric(rawValue: try need("metric")) else { throw AnalyticsError.missing("Unknown metric.") } |
| 168 | let ids = Set(a["site_ids"] as? [String] ?? []) |
| 169 | let dayKeys = DayKey.lastDays(days) |
| 170 | let pts = try store.points().filter { $0.metric == metric && dayKeys.contains($0.day) && (ids.isEmpty || ids.contains($0.subject)) && (s("event") == nil || $0.event == s("event")) } |
| 171 | let wanted = s("breakdown") |
| 172 | let rows = pts.filter { wanted == nil ? $0.breakdown == nil : ($0.breakdown?.hasPrefix(wanted! + ":") ?? false) } |
| 173 | .sorted { ($0.day, $0.subject) < ($1.day, $1.subject) } |
| 174 | .map { ["day": $0.day, "subject": $0.subject, "breakdown": orNull($0.breakdown), "value": $0.value] as [String: Any] } |
| 175 | return ["metric": metric.rawValue, "days": days, "rows": rows] |
| 176 | case "compare_periods": |
| 177 | guard let metric = Metric(rawValue: try need("metric")) else { throw AnalyticsError.missing("Unknown metric.") } |
| 178 | let ids = Set(a["site_ids"] as? [String] ?? []) |
| 179 | let both = DayKey.lastDays(days * 2), recent = Set(both.suffix(days)), prior = Set(both.prefix(days)) |
| 180 | let pts = try store.points().filter { $0.metric == metric && $0.breakdown == nil && (ids.isEmpty || ids.contains($0.subject)) } |
| 181 | let subjects = Set(pts.map(\.subject)).sorted() |
| 182 | return ["metric": metric.rawValue, "days": days, "rows": subjects.map { subj -> [String: Any] in |
| 183 | let cur = pts.filter { $0.subject == subj && recent.contains($0.day) }.reduce(0) { $0 + $1.value } |
| 184 | let prev = pts.filter { $0.subject == subj && prior.contains($0.day) }.reduce(0) { $0 + $1.value } |
| 185 | return ["subject": subj, "current": cur, "previous": prev, "change_percent": orNull(prev > 0 ? ((cur - prev) / prev * 100).rounded() : nil)] |
| 186 | }] |
| 187 | case "discover_ga4_properties": |
| 188 | let tracked = Set(ws.sites.compactMap(\.ga4PropertyID)) |
| 189 | return ["properties": try await discover().map { ["id": $0.id, "name": $0.name, "account": $0.account, "tracked": tracked.contains($0.id)] }] |
| 190 | case "add_site": |
| 191 | let siteName = try need("name"), property = try need("ga4_property_id") |
| 192 | guard property.allSatisfy(\.isNumber) else { throw AnalyticsError.missing("ga4_property_id is the numeric property ID, e.g. 564127557.") } |
| 193 | var created: Site? |
| 194 | try write("add_site", "Added \(siteName) (GA4 \(property))") { ws in |
| 195 | guard !ws.sites.contains(where: { $0.ga4PropertyID == property && !$0.archived }) else { throw AnalyticsError.notAllowed("That property is already tracked.") } |
| 196 | let site = Site(id: Self.slug(siteName, taken: Set(ws.sites.map(\.id))), name: siteName, url: s("url").flatMap(URL.init(string:)), |
| 197 | ga4PropertyID: property, colorIndex: ws.sites.count % 7) |
| 198 | ws.sites.append(site); created = site |
| 199 | } |
| 200 | return ["site_id": created?.id ?? "", "next": "Call refresh_all to load its numbers."] |
| 201 | case "update_site": |
| 202 | let id = try need("site_id") |
| 203 | try write("update_site", "Updated site \(id)") { ws in |
| 204 | guard let i = ws.sites.firstIndex(where: { $0.id == id }) else { throw AnalyticsError.missing("No site \(id).") } |
| 205 | if let v = s("name") { ws.sites[i].name = v } |
| 206 | if let v = s("ga4_property_id") { ws.sites[i].ga4PropertyID = v } |
| 207 | if let v = s("url") { ws.sites[i].url = URL(string: v) } |
| 208 | ws.sites[i].archived = false |
| 209 | } |
| 210 | return ["ok": true] |
| 211 | case "archive_site": |
| 212 | let id = try need("site_id") |
| 213 | try write("archive_site", "Archived site \(id)") { ws in |
| 214 | guard let i = ws.sites.firstIndex(where: { $0.id == id }) else { throw AnalyticsError.missing("No site \(id).") } |
| 215 | ws.sites[i].archived = true |
| 216 | } |
| 217 | return ["ok": true] |
| 218 | case "add_app": |
| 219 | let appID = try need("apple_id"), appName = try need("name") |
| 220 | try write("add_app", "Added app \(appName) (\(appID))") { ws in |
| 221 | ws.apps.removeAll { $0.id == appID } |
| 222 | ws.apps.append(StoreApp(id: appID, name: appName, siteID: s("site_id"))) |
| 223 | } |
| 224 | return ["ok": true] |
| 225 | case "create_dashboard": |
| 226 | let dashName = try need("name"); var id = "" |
| 227 | try write("create_dashboard", "Created dashboard “\(dashName)”") { ws in |
| 228 | id = Self.slug(dashName, taken: Set(ws.dashboards.map(\.id))) |
| 229 | ws.dashboards.append(Dashboard(id: id, name: dashName, widgets: [])) |
| 230 | } |
| 231 | return ["dashboard_id": id] |
| 232 | case "add_widget": |
| 233 | let dash = try need("dashboard_id"), title = try need("title") |
| 234 | guard let kind = Widget.Kind(rawValue: try need("kind")), let metric = Metric(rawValue: try need("metric")) else { throw AnalyticsError.missing("Unknown kind or metric.") } |
| 235 | var wid = "" |
| 236 | try write("add_widget", "Added “\(title)” to \(dash)") { ws in |
| 237 | guard let i = ws.dashboards.firstIndex(where: { $0.id == dash }) else { throw AnalyticsError.missing("No dashboard \(dash).") } |
| 238 | wid = Self.slug(title, taken: Set(ws.dashboards[i].widgets.map(\.id))) |
| 239 | ws.dashboards[i].widgets.append(Widget(id: wid, title: title, kind: kind, metric: metric, subjects: a["site_ids"] as? [String] ?? [], |
| 240 | days: days, breakdown: s("breakdown"), event: s("event"))) |
| 241 | } |
| 242 | return ["widget_id": wid] |
| 243 | case "remove_widget": |
| 244 | let dash = try need("dashboard_id"), wid = try need("widget_id") |
| 245 | try write("remove_widget", "Removed widget \(wid) from \(dash)") { ws in |
| 246 | guard let i = ws.dashboards.firstIndex(where: { $0.id == dash }) else { throw AnalyticsError.missing("No dashboard \(dash).") } |
| 247 | ws.dashboards[i].widgets.removeAll { $0.id == wid } |
| 248 | } |
| 249 | return ["ok": true] |
| 250 | case "refresh_all": |
| 251 | let report = await refresh() |
| 252 | try write("refresh_all", "Refreshed \(report.updated.count) sources" + (report.failed.isEmpty ? "" : ", \(report.failed.count) failed")) { _ in } |
| 253 | return ["updated": report.updated, "failed": report.failed, "skipped": report.skipped, "points": report.points] |
| 254 | case "set_app_store_key": |
| 255 | guard let pem = environment["GRAPHLEY_ASC_PRIVATE_KEY"]?.nilIfEmpty else { |
| 256 | throw AnalyticsError.missing("Start this MCP process with GRAPHLEY_ASC_PRIVATE_KEY set to the .p8 contents (from your secret manager).") |
| 257 | } |
| 258 | if AppStoreConnect().isConfigured && a["replace_existing"] as? Bool != true { |
| 259 | throw AnalyticsError.notAllowed("A key is already saved. Pass replace_existing: true to change it.") |
| 260 | } |
| 261 | try Keychain.set(try need("key_id"), for: .appStoreKeyID) |
| 262 | try Keychain.set(try need("issuer_id"), for: .appStoreIssuerID) |
| 263 | try Keychain.set(try need("vendor_number"), for: .appStoreVendorNumber) |
| 264 | try Keychain.set(pem, for: .appStorePrivateKey) |
| 265 | try write("set_app_store_key", "Saved an App Store Connect key") { _ in } |
| 266 | return ["saved": true] |
| 267 | case "setup_portfolio": |
| 268 | try write("setup_portfolio", "Set up every portfolio site, app, account, campaign and dashboard") { ws in Portfolio.apply(to: &ws) } |
| 269 | let apps = try store.load().apps |
| 270 | try store.mutatePoints { Portfolio.migrate(&$0, apps: apps) } |
| 271 | let ws = try store.load() |
| 272 | return ["sites": ws.sites.filter { !$0.archived }.map(\.name), "apps": ws.apps.map(\.name), "dashboards": ws.dashboards.map(\.name), |
| 273 | "next": "Call refresh_all to load the numbers."] |
| 274 | case "import_history": |
| 275 | let kind = try need("kind") |
| 276 | guard let rows = a["rows"] as? [[String: Any]] else { throw AnalyticsError.missing("rows is required.") } |
| 277 | let imported = try Portfolio.importHistory(kind: kind, rows: rows, store: store, markSent: a["mark_reviews_sent"] as? Bool == true) |
| 278 | try write("import_history", "Imported \(imported) \(kind) rows") { _ in } |
| 279 | return ["imported": imported] |
| 280 | case "record_followers": |
| 281 | let account = try need("account_id") |
| 282 | guard let count = a["count"] as? Int else { throw AnalyticsError.missing("count is required.") } |
| 283 | guard ws.socials.contains(where: { $0.id == account }) else { throw AnalyticsError.missing("No account \(account). Call setup_portfolio first.") } |
| 284 | let day = s("day") ?? DayKey.string(.now) |
| 285 | try store.merge([DataPoint(day: day, subject: account, metric: .followers, value: Double(count))]) |
| 286 | try write("record_followers", "Recorded \(count) followers for \(account) on \(day)") { _ in } |
| 287 | return ["ok": true] |
| 288 | case "export_backup": |
| 289 | return ["format": "graphley-backup-1", "exported_at": ISO8601DateFormatter().string(from: .now), |
| 290 | "workspace": try JSONSerialization.jsonObject(with: JSONEncoder.analytics.encode(ws)), |
| 291 | "points": try JSONSerialization.jsonObject(with: JSONEncoder.analytics.encode(try store.points()))] |
| 292 | case "list_reviews": |
| 293 | let reviews = ws.reviews ?? [] |
| 294 | return ["reviews": reviews.map { ["review_id": $0.id, "app": $0.appName, "stars": $0.stars, "title": $0.title, "country": $0.country, |
| 295 | "date": $0.date, "first_seen": $0.firstSeen] as [String: Any] }, |
| 296 | "pending_todos": (ws.pendingTodos ?? []).map(\.key), "sent_todos": (ws.todoKeys ?? []).count] |
| 297 | case "set_source_key": |
| 298 | let source = try need("source") |
| 299 | let items: [String: Keychain.Item] = ["bing": .bingAPIKey, "x": .xBearerToken, "instagram": .instagramToken, "opentalon": .openTalonConnection] |
| 300 | guard let item = items[source] else { throw AnalyticsError.missing("Unknown source \(source).") } |
| 301 | guard let value = environment["GRAPHLEY_SOURCE_KEY"]?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty else { |
| 302 | throw AnalyticsError.missing("Start this MCP process with GRAPHLEY_SOURCE_KEY set to the key (from your secret manager).") |
| 303 | } |
| 304 | if source == "opentalon" { |
| 305 | guard let o = try? JSONSerialization.jsonObject(with: Data(value.utf8)) as? [String: Any], o["token"] is String, o["port"] != nil |
| 306 | else { throw AnalyticsError.missing("For opentalon, GRAPHLEY_SOURCE_KEY is the JSON with port and token.") } |
| 307 | } |
| 308 | if Keychain.has(item) && a["replace_existing"] as? Bool != true { |
| 309 | throw AnalyticsError.notAllowed("A \(source) key is already saved. Pass replace_existing: true to change it.") |
| 310 | } |
| 311 | try Keychain.set(value, for: item) |
| 312 | try write("set_source_key", "Saved the \(source) key") { _ in } |
| 313 | return ["saved": true] |
| 314 | case "set_google_service_account": |
| 315 | guard let json = environment["GRAPHLEY_GOOGLE_SERVICE_ACCOUNT"]?.nilIfEmpty else { |
| 316 | throw AnalyticsError.missing("Start this MCP process with GRAPHLEY_GOOGLE_SERVICE_ACCOUNT set to the service account key JSON (from your secret manager).") |
| 317 | } |
| 318 | if Keychain.has(.googleServiceAccount) && a["replace_existing"] as? Bool != true { |
| 319 | throw AnalyticsError.notAllowed("A service account key is already saved. Pass replace_existing: true to change it.") |
| 320 | } |
| 321 | let account = try ServiceAccount(json: json) |
| 322 | try Keychain.set(json, for: .googleServiceAccount) |
| 323 | try write("set_google_service_account", "Saved a Google service account key for \(account.clientEmail)") { _ in } |
| 324 | return ["saved": true, "client_email": account.clientEmail] |
| 325 | default: |
| 326 | throw AnalyticsError.missing("Unknown tool \(name).") |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | private func write(_ tool: String, _ summary: String, _ change: (inout Workspace) throws -> Void) throws { |
| 331 | try store.update { ws in |
| 332 | try change(&ws) |
| 333 | ws.agentLog.insert(AgentAction(client: clientName, tool: tool, summary: summary), at: 0) |
| 334 | if ws.agentLog.count > 500 { ws.agentLog.removeLast(ws.agentLog.count - 500) } |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | static func slug(_ s: String, taken: Set<String>) -> String { |
| 339 | let base = s.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "-" }.joined() |
| 340 | .split(separator: "-").joined(separator: "-") |
| 341 | var candidate = base.isEmpty ? "item" : base, n = 2 |
| 342 | while taken.contains(candidate) { candidate = "\(base)-\(n)"; n += 1 } |
| 343 | return candidate |
| 344 | } |
| 345 | |
| 346 | private func success(_ id: Any, _ result: [String: Any]) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "result": result] } |
| 347 | private func failure(_ id: Any, _ code: Int, _ message: String) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "error": ["code": code, "message": message]] } |
| 348 | } |
| 349 | |
| 350 | extension String { var nilIfEmpty: String? { isEmpty ? nil : self } } |
| 351 | |
| 352 | /// JSON null for a missing value. |
| 353 | func orNull(_ value: Any?) -> Any { value ?? NSNull() } |