Skip to content

fix toolsets#1163

Merged
guitavano merged 1 commit intomainfrom
tavano/fix-toolsets
Sep 4, 2025
Merged

fix toolsets#1163
guitavano merged 1 commit intomainfrom
tavano/fix-toolsets

Conversation

@guitavano
Copy link
Copy Markdown
Contributor

@guitavano guitavano commented Sep 4, 2025

Summary by CodeRabbit

  • New Features

    • Agent chats now support configurable toolsets, enabling multiple connections (HTTP/SSE) with optional filters for more flexible tooling.
    • Toolsets are forwarded to the chat backend when provided, enabling richer, targeted interactions.
  • Refactor

    • Migrated from legacy “additional tools” mapping to a standardized toolsets structure. Existing chats continue to work without changes.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 4, 2025

Walkthrough

Replaces additionalTools mapping with a first-class toolsets array in the chat page and threads it through AgentProvider to the chat request. Updates AgentProvider’s prop types to accept Toolset[], imports Toolset, and forwards toolsets to experimental_prepareRequestBody. Other parameters and getPublicChatLink remain unchanged.

Changes

Cohort / File(s) Summary
Agent chat page toolsets migration
apps/web/src/components/agent/chats.tsx
Replaces backward-compat map with array-based toolsets parsing from URL params; updates useMemo to return toolsets; passes toolsets to AgentProvider instead of additionalTools; no other behavior changes.
Agent provider type and request update
apps/web/src/components/agent/provider.tsx
Imports Toolset from @deco/sdk; extends AgentProviderProps with optional toolsets?: Toolset[]; destructures toolsets and forwards it in experimental_prepareRequestBody for chat API calls; existing logic unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant C as Chats Component
  participant P as AgentProvider
  participant B as Chat Backend

  U->>C: Open agent chat URL
  C->>C: Parse parameters (threadId, workspaceId, toolsets[])
  C->>P: Render AgentProvider(toolsets=[...])
  note right of C: New: Pass Toolset[] instead of additionalTools

  P->>P: Prepare request body
  P->>B: chat({... , toolsets})
  B-->>P: Response
  P-->>C: Stream/Result
  C-->>U: Display chat
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I twitch my ears at arrays anew,
Toolsets hop in tidy queue.
From chat to provider, swift they go,
Packed in baskets, neat in flow.
No extra burrows, just a pass—
Thump! The payload’s fresh at last.
🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch tavano/fix-toolsets

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@cloudflare-workers-and-pages
Copy link
Copy Markdown

Deploying chat with  Cloudflare Pages  Cloudflare Pages

Latest commit: d52a75d
Status: ✅  Deploy successful!
Preview URL: https://5fdc2461.chat-46r.pages.dev
Branch Preview URL: https://tavano-fix-toolsets.chat-46r.pages.dev

View logs

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
apps/web/src/components/agent/provider.tsx (2)

68-70: Deprecate additionalTools and make toolsets read-only.

Signal the migration path and prevent accidental mutation of the array.

   children: React.ReactNode;
-  additionalTools?: Agent["tools_set"];
-  toolsets?: Toolset[];
+  /** @deprecated Use `toolsets` instead. */
+  additionalTools?: Agent["tools_set"];
+  toolsets?: readonly Toolset[];

287-306: Only send toolsets when non-empty to preserve server defaults.

Sending an empty array may override server-side defaults. Omit the field if there are no toolsets.

-      return {
+      const sanitizedToolsets = toolsets && toolsets.length > 0 ? toolsets : undefined;
+      return {
         metadata: { threadId: threadId ?? agentId },
         args: [
           [lastMessage],
           {
             model: mergedUiOptions.showModelSelector
               ? preferences.defaultModel
               : effectiveChatState.model,
             instructions: effectiveChatState.instructions,
             bypassOpenRouter,
             sendReasoning: preferences.sendReasoning ?? true,
             tools: effectiveChatState.tools_set,
             maxSteps: effectiveChatState.max_steps,
             pdfSummarization: preferences.pdfSummarization ?? true,
-            toolsets,
+            toolsets: sanitizedToolsets,
             smoothStream:
               preferences.smoothStream !== false
                 ? { delayInMs: 25, chunk: "word" }
                 : undefined,
           },
         ],
       };
apps/web/src/components/agent/chats.tsx (1)

114-115: Don’t pass an empty toolsets array; prefer undefined.

Keeps semantics clear and avoids overriding backend defaults.

-            toolsets={toolsets}
+            toolsets={toolsets.length ? toolsets : undefined}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5009850 and d52a75d.

📒 Files selected for processing (2)
  • apps/web/src/components/agent/chats.tsx (2 hunks)
  • apps/web/src/components/agent/provider.tsx (4 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/data-flow.mdc)

**/*.{ts,tsx}: MCP tools must use Zod schemas for input and, when applicable, output validation
Register tools with server.registerTool providing description, inputSchema.shape, and optional outputSchema.shape
In every MCP tool handler, perform authorization checks first and then call context.resourceAccess.grant() before business logic
Name tools using the {RESOURCE}_{ACTION} pattern (e.g., AGENTS_CREATE, THREADS_LIST)
Group related tools into typed collections (e.g., GLOBAL_TOOLS, WORKSPACE_TOOLS) and export them as const
Always check workspace/team access before executing operations that touch workspace resources
Return proper authorization errors and handle forbidden operations explicitly

**/*.{ts,tsx}: Use functional and declarative programming patterns; avoid classes
Favor iteration and modularization to adhere to DRY and avoid duplication
Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
Organize files so each file contains only related content (components, subcomponents, helpers, static content, types)
Favor named exports for functions
Prefer interfaces over types for object shapes
Avoid enums; use maps instead for better type safety and flexibility
Use the function keyword for pure functions to benefit from hoisting and clarity

Files:

  • apps/web/src/components/agent/provider.tsx
  • apps/web/src/components/agent/chats.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/data-flow.mdc)

**/*.tsx: Use the shared KEYS object to construct consistent React Query keys
Use useSuspenseQuery for critical data fetching hooks
Implement optimistic updates for mutations and provide rollback on error via onMutate/onError
After successful mutations, update relevant caches with setQueryData (e.g., entity detail and list keys)
Leverage React Query’s built-in request deduplication instead of manual throttling
Use parallel queries where appropriate to reduce total load time

**/*.tsx: Use functional React components with TypeScript interfaces
Prefer using UI components from @deco/ui (packages/ui) instead of custom duplicates
Memoize expensive computations in components using useMemo
Memoize objects and arrays (e.g., defaultValues) to keep stable references
Use useDeferredValue for search inputs to keep typing responsive
Follow MCP data-access patterns (e.g., useAgents, useIntegrations) with proper loading/error states
Always use design-system form components from @deco/ui when building forms
Prefer react-hook-form with schema validation (e.g., zod) over useState for form state
Avoid prop drilling in forms; share via context/provider pattern
Apply Single Responsibility Principle: split monolithic components into focused subcomponents
Design for composability and reusability of UI components
In hooks’ dependency arrays, ensure stable references; avoid inline object/array/function literals
Memoize options/objects used in dependencies (e.g., via useMemo)
Handle loading, error, and empty states consistently for data-driven views
Extract complex conditional/rendering logic into components instead of IIFEs inside JSX

Files:

  • apps/web/src/components/agent/provider.tsx
  • apps/web/src/components/agent/chats.tsx
apps/web/**

📄 CodeRabbit inference engine (.cursor/rules/structure.mdc)

Place the main application UI (Vite SPA) under /apps/web

Files:

  • apps/web/src/components/agent/provider.tsx
  • apps/web/src/components/agent/chats.tsx
{apps/web,packages/ui}/**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/structure.mdc)

Build UI components with React 19

Files:

  • apps/web/src/components/agent/provider.tsx
  • apps/web/src/components/agent/chats.tsx
{apps/web,packages/ui}/**/*.{tsx,jsx,css}

📄 CodeRabbit inference engine (.cursor/rules/structure.mdc)

Use Tailwind CSS v4 for styling

Files:

  • apps/web/src/components/agent/provider.tsx
  • apps/web/src/components/agent/chats.tsx
apps/web/**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (apps/web/.cursor/rules/posthog-integration.mdc)

apps/web/**/*.{js,jsx,ts,tsx}: Use each feature flag in as few places as possible; if a flag must appear at multiple callsites, explicitly flag this for careful developer review
Gate any flag-dependent code behind checks that verify the flag’s values are valid and expected
If a custom person or event property is referenced in two or more files or at two or more callsites in the same file, centralize the keys in an enum (TS) or const object (JS)

Files:

  • apps/web/src/components/agent/provider.tsx
  • apps/web/src/components/agent/chats.tsx
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/.cursor/rules/posthog-integration.mdc)

In TypeScript, store feature flag names in an enum with members written UPPERCASE_WITH_UNDERSCORE and use a consistent naming convention

Files:

  • apps/web/src/components/agent/provider.tsx
  • apps/web/src/components/agent/chats.tsx
🧠 Learnings (2)
📚 Learning: 2025-09-03T18:47:09.806Z
Learnt from: CR
PR: deco-cx/chat#0
File: apps/deconfig/.cursor/rules/ai-usage.mdc:0-0
Timestamp: 2025-09-03T18:47:09.806Z
Learning: Applies to apps/deconfig/server/**/*.ts : Proxy external AI tools in the server by creating a tool (e.g., id: "AI_GENERATE_OBJECT") with zod-validated input/output and forwarding to env.DECO_CHAT_WORKSPACE_API.AI_GENERATE_OBJECT

Applied to files:

  • apps/web/src/components/agent/provider.tsx
  • apps/web/src/components/agent/chats.tsx
📚 Learning: 2025-09-03T18:50:00.731Z
Learnt from: CR
PR: deco-cx/chat#0
File: apps/deconfig/.cursor/rules/tools.mdc:0-0
Timestamp: 2025-09-03T18:50:00.731Z
Learning: Applies to apps/deconfig/server/main.ts : Add new tool definitions in server/main.ts

Applied to files:

  • apps/web/src/components/agent/provider.tsx

Comment on lines +63 to +73
const toolsets = params.getAll("toolsets").map((toolset) => {
const [mcpUrl, connectionType = "HTTP"] = toolset.split(",");

return {
connection: {
type: connectionType as "HTTP" | "SSE",
url: mcpUrl,
},
filters: [],
};
});
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden parsing/validation of toolsets from URL params.

Comma-splitting is brittle (commas are valid in URLs) and unvalidated URLs/types can be abused. Normalize type, validate URL, and drop invalid entries.

-    const toolsets = params.getAll("toolsets").map((toolset) => {
-      const [mcpUrl, connectionType = "HTTP"] = toolset.split(",");
-
-      return {
-        connection: {
-          type: connectionType as "HTTP" | "SSE",
-          url: mcpUrl,
-        },
-        filters: [],
-      };
-    });
+    const toolsets = params
+      .getAll("toolsets")
+      .map((raw) => {
+        const [rawUrl, rawType = "HTTP"] = raw.split(",", 2);
+        try {
+          const url = new URL(rawUrl);
+          const type = rawType.toUpperCase() === "SSE" ? "SSE" : "HTTP";
+          if (url.protocol !== "https:" && url.protocol !== "http:") return null;
+          return {
+            connection: { type, url: url.href },
+            filters: [],
+          };
+        } catch {
+          return null;
+        }
+      })
+      .filter((v): v is { connection: { type: "HTTP" | "SSE"; url: string }; filters: string[] } => Boolean(v));
🤖 Prompt for AI Agents
In apps/web/src/components/agent/chats.tsx around lines 63 to 73, the current
comma-split parsing of toolsets is brittle and unvalidated; update parsing to
split on the last comma (so commas in the URL are preserved), trim values,
normalize the connection type to uppercase and accept only "HTTP" or "SSE"
(default to "HTTP" if invalid), validate the URL by constructing a URL object
(or using a URL validation helper) and skip any entries with invalid URLs or
unsupported types, and ensure filters remains an empty array for dropped/invalid
entries so only well-formed toolset objects are returned.

DECO_CHAT_API,
dispatchMessages,
getTraceDebugId,
Toolset,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix: import Toolset as a type to avoid runtime import errors.

Toolset is used only in type positions. Importing it as a value can emit a runtime import that @deco/sdk likely does not provide, causing bundling/runtime failures.

Apply:

-  Toolset,
+  type Toolset,
🤖 Prompt for AI Agents
In apps/web/src/components/agent/provider.tsx around line 8, the current import
brings in Toolset as a runtime value even though it is used only for typing,
which can cause bundling/runtime failures; change the import to a type-only
import (e.g., use the TypeScript "import type" form or otherwise mark Toolset as
a type-only import) so the compiler omits the runtime require and avoids
importing unavailable runtime exports from @deco/sdk.

@guitavano guitavano merged commit 1184066 into main Sep 4, 2025
7 checks passed
@guitavano guitavano deleted the tavano/fix-toolsets branch September 4, 2025 19:18
This was referenced Oct 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants