diff --git a/Docs/MCP.md b/Docs/MCP.md index 444a4a1..99aa087 100644 --- a/Docs/MCP.md +++ b/Docs/MCP.md @@ -1,5 +1,14 @@ # Programming custom MCP servers for AI Studio +## Built-in web toolset + +In **Toolbox → MCP Servers**, choose **Activate Web Toolset**. This loads +`retrieve_page` and `web_search` inside AI Studio without launching an MCP +subprocess. Choose a tool, review its JSON input and confirm the call. +Page retrieval takes a `url`. Search takes a `query` and uses the SearXNG +search URL configured in **Toolbox → Web**. You can attach returned sources +to the next chat message. + ## Connect an existing server Open **Toolbox** beside the composer. Choose **Use LM Studio Config** to read diff --git a/Docs/PHASES.md b/Docs/PHASES.md index 768653f..70f9ccd 100644 --- a/Docs/PHASES.md +++ b/Docs/PHASES.md @@ -101,3 +101,8 @@ retrieval. The local search and article fixture verified query encoding, result deduplication, extraction, and source URLs. The Debug build passed. 34 tests passed and four opt-in checks were skipped. A live SearXNG check requires the intended instance and JSON output enabled. + +**16 November 2026.** The built-in Web toolset now appears in MCP Servers +without external server setup. Both tool calls passed against the local +web fixture. The installed Local Knowledge MCP profile passed discovery. +The Debug build passed with 37 tests passing and three opt-in checks skipped. diff --git a/README.md b/README.md index 124f321..3c7f2d0 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,8 @@ open a browser search and paste the chosen URL into **Retrieve Page**. Retrieval extracts text from UTF-8 HTML and plain-text pages without running page scripts. It keeps the final source URL. Attach an individual result or a retrieved page to your next message after reviewing it. +Choose **Activate Web Toolset** in the **MCP Servers** tab to access the same +operations through the Toolbox tool list. ## Build and test diff --git a/Sources/MCP.swift b/Sources/MCP.swift index ecfc76d..deaab1e 100644 --- a/Sources/MCP.swift +++ b/Sources/MCP.swift @@ -225,7 +225,8 @@ struct MCPSettings: View { @AppStorage("mcpExecutable") private var executable = "" @AppStorage("mcpArguments") private var launchArguments = "" private var client: (any MCPToolClient)? { studio.activeToolset?.client } - @State private var confirmLaunch = false + @AppStorage("webSearchEndpoint") private var webSearchEndpoint = "" + @State private var confirmingStartup = false @AppStorage("mcpConfigPath") private var configPath = "" @AppStorage("mcpSelectedProfile") private var selectedProfile = "" @State private var profiles: [String: MCPServerConfiguration] = [:] @@ -246,6 +247,15 @@ struct MCPSettings: View { var body: some View { Form { + Section("Built-In Tools") { + Button("Activate Web Toolset", action: activateWeb).disabled(busy) + if client is BuiltInWebTools { + LabeledContent("Connection", value: "Active") + Button("Disconnect Web Toolset") { resetConnection() }.disabled(busy) + } + Text("Retrieve pages directly. Search uses the SearXNG endpoint configured in Toolbox → Web.") + .foregroundStyle(.secondary) + } Section("Custom MCP Servers") { HStack { Button("Import mcp.json…") { importingConfig = true } @@ -285,7 +295,7 @@ struct MCPSettings: View { } HStack { Button(local ? "Start Server and Discover…" : "Discover Tools") { - if local { confirmLaunch = true } + if local { confirmingStartup = true; confirm = true } else { discover() } } .disabled(busy || target.isEmpty) @@ -311,7 +321,7 @@ struct MCPSettings: View { } TextEditor(text: $arguments).font(.system(.body, design: .monospaced)) .frame(height: 80).accessibilityLabel("JSON arguments") - Button("Review Tool Call…") { confirm = true }.disabled(busy) + Button("Review Tool Call…") { confirmingStartup = false; confirm = true }.disabled(busy) } } if !result.isEmpty { @@ -347,15 +357,27 @@ struct MCPSettings: View { .onChange(of: executable) { _, _ in resetConnection() } .onChange(of: launchArguments) { _, _ in resetConnection() } .onDisappear { operation?.cancel() } - .confirmationDialog("Start local MCP server?", isPresented: $confirmLaunch, titleVisibility: .visible) { - Button("Start and Discover", action: discover) + .confirmationDialog(confirmingStartup ? "Start local MCP server?" : "Run \(name)?", + isPresented: $confirm, titleVisibility: .visible) { + if confirmingStartup { Button("Start and Discover", action: discover) } + else { Button("Run Tool", action: invoke) } } message: { - Text("Launch \(target) with its configured arguments using your macOS account.") + if confirmingStartup { + Text("Launch \(target) with its configured arguments using your macOS account.") + } else { + Text("Send these arguments to \(studio.activeToolset?.name ?? target):\n\(arguments.prefix(800))") + } } - .confirmationDialog("Run \(name)?", isPresented: $confirm, titleVisibility: .visible) { - Button("Run Tool", action: invoke) - } message: { - Text("Send these arguments to \(target):\n\(arguments.prefix(800))") + } + + private func activateWeb() { + run { + let server = BuiltInWebTools(searchEndpoint: webSearchEndpoint) + let discovered = try await server.listTools() + try Task.checkCancellation() + studio.activeToolset = ActiveToolset(name: BuiltInWebTools.name, client: server, tools: discovered) + name = discovered.first?.name ?? "" + result = "\(discovered.count) built-in tools available." } } @@ -368,7 +390,11 @@ struct MCPSettings: View { profiles = file.mcpServers configPath = url.path if profiles[selectedProfile] == nil && (disconnect || !selectedProfile.isEmpty) { - selectedProfile = profiles.keys.sorted().first ?? "" + let names = profiles.keys.sorted() + selectedProfile = names.first { name in + guard let profile = profiles[name] else { return false } + return (try? profile.makeClient()) != nil + } ?? names.first ?? "" } configStatus = "\(profiles.count) custom server(s) loaded from \(url.lastPathComponent)." } catch { @@ -401,8 +427,10 @@ struct MCPSettings: View { guard let client, !name.isEmpty else { return } let tool = name let data = Data(arguments.utf8) + let configuredClient: any MCPToolClient = client is BuiltInWebTools + ? BuiltInWebTools(searchEndpoint: webSearchEndpoint) : client run { - let output = try await client.callTool(tool, argumentsJSON: data) + let output = try await configuredClient.callTool(tool, argumentsJSON: data) try Task.checkCancellation() result = String(decoding: output, as: UTF8.self) invokedTool = tool @@ -753,3 +781,39 @@ struct ActiveToolset { let client: any MCPToolClient let tools: [MCPTool] } + +struct BuiltInWebTools: MCPToolClient { + static let name = "Built-In Web" + let searchEndpoint: String + + func listTools() async throws -> [MCPTool] { + [ + MCPTool(name: "retrieve_page", description: "Retrieve readable text from an HTTP or HTTPS page.", + inputSchemaJSON: Data(#"{"type":"object","properties":{"url":{"type":"string","format":"uri"}},"required":["url"]}"#.utf8)), + MCPTool(name: "web_search", description: "Search via the SearXNG endpoint configured in Toolbox → Web.", + inputSchemaJSON: Data(#"{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}"#.utf8)) + ] + } + + func callTool(_ name: String, argumentsJSON: Data) async throws -> Data { + let arguments = try HTTPMCPClient.arguments(argumentsJSON) + switch name { + case "retrieve_page": + guard let address = arguments["url"] as? String else { throw StudioError("Provide a page URL in the url field.") } + let page = try await WebClipCapture.page(from: address) + return try JSONSerialization.data(withJSONObject: ["url": page.url.absoluteString, "text": page.text], + options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) + case "web_search": + guard let query = arguments["query"] as? String else { throw StudioError("Provide a search query in the query field.") } + guard !searchEndpoint.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw StudioError("Set a SearXNG search URL in Toolbox → Web before using web_search.") + } + let results = try await WebSearch.results(endpoint: searchEndpoint, query: query) + return try JSONSerialization.data(withJSONObject: results.map { + ["title": $0.title, "url": $0.url.absoluteString, "snippet": $0.snippet] + }, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) + default: + throw StudioError("Unknown built-in tool: \(name).") + } + } +} diff --git a/Tests/StudioTests.swift b/Tests/StudioTests.swift index 8a0b72c..08a366c 100644 --- a/Tests/StudioTests.swift +++ b/Tests/StudioTests.swift @@ -571,3 +571,32 @@ final class WebToolsTests: XCTestCase { XCTAssertTrue(page.reference.contains(result.url.absoluteString)) } } + +final class BuiltInToolsetTests: XCTestCase { + func testDiscoveryAndSetupErrorWithoutExternalServer() async throws { + let client = BuiltInWebTools(searchEndpoint: "") + let tools = try await client.listTools() + XCTAssertEqual(tools.map(\.name), ["retrieve_page", "web_search"]) + do { + _ = try await client.callTool("web_search", argumentsJSON: Data(#"{"query":"tides"}"#.utf8)) + XCTFail("Expected a configuration error") + } catch let error as StudioError { + XCTAssertTrue(error.message.contains("SearXNG")) + } + } + + func testBuiltInToolsReturnSourcesThroughMCPInterface() async throws { + guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_WEB_URL"] else { + throw XCTSkip("Run Scripts/test.sh to configure the web fixture.") + } + let client: any MCPToolClient = BuiltInWebTools(searchEndpoint: endpoint) + let result = try await client.callTool("web_search", argumentsJSON: Data(#"{"query":"tides & moon"}"#.utf8)) + let items = try XCTUnwrap(JSONSerialization.jsonObject(with: result) as? [[String: String]]) + let address = try XCTUnwrap(items.first?["url"]) + let args = try JSONEncoder().encode(["url": address]) + let response = try await client.callTool("retrieve_page", argumentsJSON: args) + let page = try XCTUnwrap(JSONSerialization.jsonObject(with: response) as? [String: String]) + XCTAssertEqual(page["url"], address) + XCTAssertEqual(page["text"], "Moon and tides\nTest passage.") + } +}