import Foundation /// STDIO MCP server, run as ` --mcp` (the Inkspring pattern): it reads and writes the /// same local store as the app, so an agent can set everything up while the app shows the result. /// Every write is logged to `Workspace.agentLog` and shown in the app's Agents screen. public final class MCPServer: @unchecked Sendable { let store: WorkspaceStore let environment: [String: String] var clientName = "Agent" let refresh: @Sendable () async -> Refresher.Report let discover: @Sendable () async throws -> [GoogleAnalytics.Property] public init(store: WorkspaceStore, environment: [String: String] = ProcessInfo.processInfo.environment, refresh: (@Sendable () async -> Refresher.Report)? = nil, discover: (@Sendable () async throws -> [GoogleAnalytics.Property])? = nil) { self.store = store self.environment = environment self.refresh = refresh ?? { await Refresher(store: store, cloud: SnapshotSync()).refreshAll() } self.discover = discover ?? { try await GoogleAnalytics().properties() } } struct Tool { let name: String, summary: String var fields: [String: [String: Any]] = [:] var required: [String] = [] var writes = false, network = false, credentials = false var json: [String: Any] { ["name": name, "description": summary, "inputSchema": ["type": "object", "properties": fields, "required": required, "additionalProperties": false], "annotations": ["readOnlyHint": !writes, "destructiveHint": false, "openWorldHint": network]] } } // JSON schema fragments. Computed because `[String: Any]` isn't Sendable and can't be a shared static. static var str: [String: Any] { ["type": "string"] } static var int: [String: Any] { ["type": "integer", "minimum": 1, "maximum": 400] } static var strs: [String: Any] { ["type": "array", "items": ["type": "string"]] } static var metric: [String: Any] { ["type": "string", "enum": Metric.allCases.map(\.rawValue)] } static var kind: [String: Any] { ["type": "string", "enum": Widget.Kind.allCases.map(\.rawValue)] } static var tools: [Tool] { [ .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."), .init(name: "list_sites", summary: "List tracked websites with their IDs and GA4 property IDs."), .init(name: "list_apps", summary: "List tracked App Store apps."), .init(name: "list_dashboards", summary: "List dashboards and their widgets."), .init(name: "query_metric", summary: "Daily values for a metric. Omit site_ids for all sites. breakdown can be 'page' or 'platform'.", fields: ["metric": metric, "site_ids": strs, "days": int, "breakdown": str, "event": str], required: ["metric"]), .init(name: "compare_periods", summary: "Total for the last N days vs the N days before, per site, with percent change.", fields: ["metric": metric, "site_ids": strs, "days": int], required: ["metric"]), .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), .init(name: "add_site", summary: "Track a website. Use the property ID from discover_ga4_properties.", fields: ["name": str, "ga4_property_id": str, "url": str], required: ["name", "ga4_property_id"], writes: true), .init(name: "update_site", summary: "Rename a site or change its GA4 property or URL.", fields: ["site_id": str, "name": str, "ga4_property_id": str, "url": str], required: ["site_id"], writes: true), .init(name: "archive_site", summary: "Stop tracking a site. Its history is kept and it can be restored.", fields: ["site_id": str], required: ["site_id"], writes: true), .init(name: "add_app", summary: "Track an App Store app by its Apple ID, optionally linked to its website.", fields: ["apple_id": str, "name": str, "site_id": str], required: ["apple_id", "name"], writes: true), .init(name: "create_dashboard", summary: "Create an empty dashboard.", fields: ["name": str], required: ["name"], writes: true), .init(name: "add_widget", summary: "Add a chart or number to a dashboard.", fields: ["dashboard_id": str, "title": str, "kind": kind, "metric": metric, "site_ids": strs, "days": int, "breakdown": str, "event": str], required: ["dashboard_id", "title", "kind", "metric"], writes: true), .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), .init(name: "refresh_all", summary: "Pull fresh numbers from Google Analytics and App Store Connect now, then sync to iPhone.", writes: true, network: true), .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.", fields: ["key_id": str, "issuer_id": str, "vendor_number": str, "replace_existing": ["type": "boolean"]], required: ["key_id", "issuer_id", "vendor_number"], writes: true, credentials: true), .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), .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.", fields: ["kind": ["type": "string", "enum": ["followers", "videos", "ads", "ratings", "reviews"]], "rows": ["type": "array", "items": ["type": "object"]], "mark_reviews_sent": ["type": "boolean"]], required: ["kind", "rows"], writes: true), .init(name: "record_followers", summary: "Record today's (or a given day's) follower count for an account without an API (Substack, LinkedIn).", fields: ["account_id": str, "count": ["type": "integer", "minimum": 0], "day": str], required: ["account_id", "count"], writes: true), .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."), .init(name: "list_reviews", summary: "Written App Store reviews with the day each was first seen, and the review to-dos waiting for OpenTalon."), .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.", fields: ["source": ["type": "string", "enum": ["bing", "x", "instagram", "opentalon"]], "replace_existing": ["type": "boolean"]], required: ["source"], writes: true, credentials: true), .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.", fields: ["replace_existing": ["type": "boolean"]], writes: true, credentials: true) ] } // MARK: Transport public func run() async { let input = FileHandle.standardInput, output = FileHandle.standardOutput var line = Data() while true { let chunk = input.availableData if chunk.isEmpty { if !line.isEmpty { await respond(line, output) }; return } for byte in chunk { if byte == 10 { if !line.isEmpty { await respond(line, output) }; line.removeAll(keepingCapacity: true) } else if line.count < 1_048_576 { line.append(byte) } } } } private func respond(_ data: Data, _ output: FileHandle) async { let reply: [String: Any]? if let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] { reply = await handle(request) } else { reply = failure(NSNull(), -32700, "Parse error.") } if let reply, var json = try? JSONSerialization.data(withJSONObject: reply) { json.append(10); try? output.write(contentsOf: json) } } public func handle(_ request: [String: Any]) async -> [String: Any]? { let id = request["id"] ?? NSNull() guard let method = request["method"] as? String else { return failure(id, -32600, "Invalid request.") } guard request["id"] != nil else { return nil } // notification let params = request["params"] as? [String: Any] ?? [:] switch method { case "initialize": if let info = params["clientInfo"] as? [String: Any], let name = info["name"] as? String { clientName = name } let supported = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"] let asked = params["protocolVersion"] as? String ?? "" return success(id, ["protocolVersion": supported.contains(asked) ? asked : supported[0], "capabilities": ["tools": ["listChanged": false]], "serverInfo": ["name": "graphley", "version": "0.1.10"], "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."]) case "ping": return success(id, [:]) case "tools/list": return success(id, ["tools": Self.tools.map(\.json)]) case "tools/call": let name = params["name"] as? String ?? "" let args = params["arguments"] as? [String: Any] ?? [:] do { let result = try await call(name, args) let text = String(decoding: try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]), as: UTF8.self) return success(id, ["content": [["type": "text", "text": text]], "structuredContent": result]) } catch { return success(id, ["content": [["type": "text", "text": error.localizedDescription]], "isError": true]) } default: return failure(id, -32601, "Unknown method \(method).") } } // MARK: Tools func call(_ name: String, _ a: [String: Any]) async throws -> [String: Any] { guard let tool = Self.tools.first(where: { $0.name == name }) else { throw AnalyticsError.missing("Unknown tool \(name).") } let ws = try store.load() if tool.writes && !ws.settings.agentsCanWrite { throw AnalyticsError.notAllowed("Turn on “Let agents make changes” in Settings → Agents.") } if tool.credentials && !ws.settings.agentsCanSetKeys { throw AnalyticsError.notAllowed("Turn on “Let agents set keys” in Settings → Agents.") } func s(_ k: String) -> String? { (a[k] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty } func need(_ k: String) throws -> String { guard let v = s(k) else { throw AnalyticsError.missing("\(k) is required.") }; return v } let days = a["days"] as? Int ?? 30 switch name { case "get_status": let pts = try store.points() return ["sites": ws.sites.filter { !$0.archived }.count, "apps": ws.apps.count, "dashboards": ws.dashboards.count, "latest_day": orNull(pts.map(\.day).max()), "last_refresh_at": orNull(ws.settings.lastRefreshAt?.ISO8601Format()), "share_with_iphone": ws.settings.shareWithIPhone, "last_shared_at": orNull(ws.settings.lastSharedAt?.ISO8601Format()), "google_signed_in": GoogleAuth.isConfigured, "google_service_account": Keychain.has(.googleServiceAccount), "app_store_connect_key": AppStoreConnect().isConfigured, "bing_key": BingWebmaster.isConfigured, "x_token": Keychain.has(.xBearerToken), "instagram_token": Keychain.has(.instagramToken), "opentalon_connection": OpenTalonTodos.isConfigured, "socials": ws.socials.count, "reviews": (ws.reviews ?? []).count, "campaigns": (ws.campaigns ?? []).count, "agents_can_write": ws.settings.agentsCanWrite, "agents_can_set_keys": ws.settings.agentsCanSetKeys] case "list_sites": 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] }] case "list_apps": return ["apps": ws.apps.map { ["apple_id": $0.id, "name": $0.name, "site_id": orNull($0.siteID)] }] case "list_dashboards": return ["dashboards": try JSONSerialization.jsonObject(with: JSONEncoder.analytics.encode(ws.dashboards))] case "query_metric": guard let metric = Metric(rawValue: try need("metric")) else { throw AnalyticsError.missing("Unknown metric.") } let ids = Set(a["site_ids"] as? [String] ?? []) let dayKeys = DayKey.lastDays(days) 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")) } let wanted = s("breakdown") let rows = pts.filter { wanted == nil ? $0.breakdown == nil : ($0.breakdown?.hasPrefix(wanted! + ":") ?? false) } .sorted { ($0.day, $0.subject) < ($1.day, $1.subject) } .map { ["day": $0.day, "subject": $0.subject, "breakdown": orNull($0.breakdown), "value": $0.value] as [String: Any] } return ["metric": metric.rawValue, "days": days, "rows": rows] case "compare_periods": guard let metric = Metric(rawValue: try need("metric")) else { throw AnalyticsError.missing("Unknown metric.") } let ids = Set(a["site_ids"] as? [String] ?? []) let both = DayKey.lastDays(days * 2), recent = Set(both.suffix(days)), prior = Set(both.prefix(days)) let pts = try store.points().filter { $0.metric == metric && $0.breakdown == nil && (ids.isEmpty || ids.contains($0.subject)) } let subjects = Set(pts.map(\.subject)).sorted() return ["metric": metric.rawValue, "days": days, "rows": subjects.map { subj -> [String: Any] in let cur = pts.filter { $0.subject == subj && recent.contains($0.day) }.reduce(0) { $0 + $1.value } let prev = pts.filter { $0.subject == subj && prior.contains($0.day) }.reduce(0) { $0 + $1.value } return ["subject": subj, "current": cur, "previous": prev, "change_percent": orNull(prev > 0 ? ((cur - prev) / prev * 100).rounded() : nil)] }] case "discover_ga4_properties": let tracked = Set(ws.sites.compactMap(\.ga4PropertyID)) return ["properties": try await discover().map { ["id": $0.id, "name": $0.name, "account": $0.account, "tracked": tracked.contains($0.id)] }] case "add_site": let siteName = try need("name"), property = try need("ga4_property_id") guard property.allSatisfy(\.isNumber) else { throw AnalyticsError.missing("ga4_property_id is the numeric property ID, e.g. 564127557.") } var created: Site? try write("add_site", "Added \(siteName) (GA4 \(property))") { ws in guard !ws.sites.contains(where: { $0.ga4PropertyID == property && !$0.archived }) else { throw AnalyticsError.notAllowed("That property is already tracked.") } let site = Site(id: Self.slug(siteName, taken: Set(ws.sites.map(\.id))), name: siteName, url: s("url").flatMap(URL.init(string:)), ga4PropertyID: property, colorIndex: ws.sites.count % 7) ws.sites.append(site); created = site } return ["site_id": created?.id ?? "", "next": "Call refresh_all to load its numbers."] case "update_site": let id = try need("site_id") try write("update_site", "Updated site \(id)") { ws in guard let i = ws.sites.firstIndex(where: { $0.id == id }) else { throw AnalyticsError.missing("No site \(id).") } if let v = s("name") { ws.sites[i].name = v } if let v = s("ga4_property_id") { ws.sites[i].ga4PropertyID = v } if let v = s("url") { ws.sites[i].url = URL(string: v) } ws.sites[i].archived = false } return ["ok": true] case "archive_site": let id = try need("site_id") try write("archive_site", "Archived site \(id)") { ws in guard let i = ws.sites.firstIndex(where: { $0.id == id }) else { throw AnalyticsError.missing("No site \(id).") } ws.sites[i].archived = true } return ["ok": true] case "add_app": let appID = try need("apple_id"), appName = try need("name") try write("add_app", "Added app \(appName) (\(appID))") { ws in ws.apps.removeAll { $0.id == appID } ws.apps.append(StoreApp(id: appID, name: appName, siteID: s("site_id"))) } return ["ok": true] case "create_dashboard": let dashName = try need("name"); var id = "" try write("create_dashboard", "Created dashboard “\(dashName)”") { ws in id = Self.slug(dashName, taken: Set(ws.dashboards.map(\.id))) ws.dashboards.append(Dashboard(id: id, name: dashName, widgets: [])) } return ["dashboard_id": id] case "add_widget": let dash = try need("dashboard_id"), title = try need("title") guard let kind = Widget.Kind(rawValue: try need("kind")), let metric = Metric(rawValue: try need("metric")) else { throw AnalyticsError.missing("Unknown kind or metric.") } var wid = "" try write("add_widget", "Added “\(title)” to \(dash)") { ws in guard let i = ws.dashboards.firstIndex(where: { $0.id == dash }) else { throw AnalyticsError.missing("No dashboard \(dash).") } wid = Self.slug(title, taken: Set(ws.dashboards[i].widgets.map(\.id))) ws.dashboards[i].widgets.append(Widget(id: wid, title: title, kind: kind, metric: metric, subjects: a["site_ids"] as? [String] ?? [], days: days, breakdown: s("breakdown"), event: s("event"))) } return ["widget_id": wid] case "remove_widget": let dash = try need("dashboard_id"), wid = try need("widget_id") try write("remove_widget", "Removed widget \(wid) from \(dash)") { ws in guard let i = ws.dashboards.firstIndex(where: { $0.id == dash }) else { throw AnalyticsError.missing("No dashboard \(dash).") } ws.dashboards[i].widgets.removeAll { $0.id == wid } } return ["ok": true] case "refresh_all": let report = await refresh() try write("refresh_all", "Refreshed \(report.updated.count) sources" + (report.failed.isEmpty ? "" : ", \(report.failed.count) failed")) { _ in } return ["updated": report.updated, "failed": report.failed, "skipped": report.skipped, "points": report.points] case "set_app_store_key": guard let pem = environment["GRAPHLEY_ASC_PRIVATE_KEY"]?.nilIfEmpty else { throw AnalyticsError.missing("Start this MCP process with GRAPHLEY_ASC_PRIVATE_KEY set to the .p8 contents (from your secret manager).") } if AppStoreConnect().isConfigured && a["replace_existing"] as? Bool != true { throw AnalyticsError.notAllowed("A key is already saved. Pass replace_existing: true to change it.") } try Keychain.set(try need("key_id"), for: .appStoreKeyID) try Keychain.set(try need("issuer_id"), for: .appStoreIssuerID) try Keychain.set(try need("vendor_number"), for: .appStoreVendorNumber) try Keychain.set(pem, for: .appStorePrivateKey) try write("set_app_store_key", "Saved an App Store Connect key") { _ in } return ["saved": true] case "setup_portfolio": try write("setup_portfolio", "Set up every portfolio site, app, account, campaign and dashboard") { ws in Portfolio.apply(to: &ws) } let apps = try store.load().apps try store.mutatePoints { Portfolio.migrate(&$0, apps: apps) } let ws = try store.load() return ["sites": ws.sites.filter { !$0.archived }.map(\.name), "apps": ws.apps.map(\.name), "dashboards": ws.dashboards.map(\.name), "next": "Call refresh_all to load the numbers."] case "import_history": let kind = try need("kind") guard let rows = a["rows"] as? [[String: Any]] else { throw AnalyticsError.missing("rows is required.") } let imported = try Portfolio.importHistory(kind: kind, rows: rows, store: store, markSent: a["mark_reviews_sent"] as? Bool == true) try write("import_history", "Imported \(imported) \(kind) rows") { _ in } return ["imported": imported] case "record_followers": let account = try need("account_id") guard let count = a["count"] as? Int else { throw AnalyticsError.missing("count is required.") } guard ws.socials.contains(where: { $0.id == account }) else { throw AnalyticsError.missing("No account \(account). Call setup_portfolio first.") } let day = s("day") ?? DayKey.string(.now) try store.merge([DataPoint(day: day, subject: account, metric: .followers, value: Double(count))]) try write("record_followers", "Recorded \(count) followers for \(account) on \(day)") { _ in } return ["ok": true] case "export_backup": return ["format": "graphley-backup-1", "exported_at": ISO8601DateFormatter().string(from: .now), "workspace": try JSONSerialization.jsonObject(with: JSONEncoder.analytics.encode(ws)), "points": try JSONSerialization.jsonObject(with: JSONEncoder.analytics.encode(try store.points()))] case "list_reviews": let reviews = ws.reviews ?? [] return ["reviews": reviews.map { ["review_id": $0.id, "app": $0.appName, "stars": $0.stars, "title": $0.title, "country": $0.country, "date": $0.date, "first_seen": $0.firstSeen] as [String: Any] }, "pending_todos": (ws.pendingTodos ?? []).map(\.key), "sent_todos": (ws.todoKeys ?? []).count] case "set_source_key": let source = try need("source") let items: [String: Keychain.Item] = ["bing": .bingAPIKey, "x": .xBearerToken, "instagram": .instagramToken, "opentalon": .openTalonConnection] guard let item = items[source] else { throw AnalyticsError.missing("Unknown source \(source).") } guard let value = environment["GRAPHLEY_SOURCE_KEY"]?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty else { throw AnalyticsError.missing("Start this MCP process with GRAPHLEY_SOURCE_KEY set to the key (from your secret manager).") } if source == "opentalon" { guard let o = try? JSONSerialization.jsonObject(with: Data(value.utf8)) as? [String: Any], o["token"] is String, o["port"] != nil else { throw AnalyticsError.missing("For opentalon, GRAPHLEY_SOURCE_KEY is the JSON with port and token.") } } if Keychain.has(item) && a["replace_existing"] as? Bool != true { throw AnalyticsError.notAllowed("A \(source) key is already saved. Pass replace_existing: true to change it.") } try Keychain.set(value, for: item) try write("set_source_key", "Saved the \(source) key") { _ in } return ["saved": true] case "set_google_service_account": guard let json = environment["GRAPHLEY_GOOGLE_SERVICE_ACCOUNT"]?.nilIfEmpty else { throw AnalyticsError.missing("Start this MCP process with GRAPHLEY_GOOGLE_SERVICE_ACCOUNT set to the service account key JSON (from your secret manager).") } if Keychain.has(.googleServiceAccount) && a["replace_existing"] as? Bool != true { throw AnalyticsError.notAllowed("A service account key is already saved. Pass replace_existing: true to change it.") } let account = try ServiceAccount(json: json) try Keychain.set(json, for: .googleServiceAccount) try write("set_google_service_account", "Saved a Google service account key for \(account.clientEmail)") { _ in } return ["saved": true, "client_email": account.clientEmail] default: throw AnalyticsError.missing("Unknown tool \(name).") } } private func write(_ tool: String, _ summary: String, _ change: (inout Workspace) throws -> Void) throws { try store.update { ws in try change(&ws) ws.agentLog.insert(AgentAction(client: clientName, tool: tool, summary: summary), at: 0) if ws.agentLog.count > 500 { ws.agentLog.removeLast(ws.agentLog.count - 500) } } } static func slug(_ s: String, taken: Set) -> String { let base = s.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "-" }.joined() .split(separator: "-").joined(separator: "-") var candidate = base.isEmpty ? "item" : base, n = 2 while taken.contains(candidate) { candidate = "\(base)-\(n)"; n += 1 } return candidate } private func success(_ id: Any, _ result: [String: Any]) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "result": result] } private func failure(_ id: Any, _ code: Int, _ message: String) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "error": ["code": code, "message": message]] } } extension String { var nilIfEmpty: String? { isEmpty ? nil : self } } /// JSON null for a missing value. func orNull(_ value: Any?) -> Any { value ?? NSNull() }