Skip to content

prompting & MCP#304

Merged
ngoiyaeric merged 3 commits intomainfrom
Prompting
Sep 30, 2025
Merged

prompting & MCP#304
ngoiyaeric merged 3 commits intomainfrom
Prompting

Conversation

@ngoiyaeric
Copy link
Collaborator

@ngoiyaeric ngoiyaeric commented Sep 30, 2025

User description

  • Fixed prompting
  • Updated MCP programming

PR Type

Enhancement


Description

  • Updated MCP server configuration and URL endpoints

  • Enhanced geospatial tool descriptions and capabilities

  • Improved tool selection logic for different query types

  • Fixed config loading with better error handling


Diagram Walkthrough

flowchart LR
  A["Config Loading"] --> B["MCP Server URL"]
  B --> C["Tool Selection Logic"]
  C --> D["Enhanced Tool Descriptions"]
  D --> E["Improved Query Processing"]
Loading

File Walkthrough

Relevant files
Enhancement
geospatial.tsx
Enhanced MCP configuration and tool capabilities                 

lib/agents/tools/geospatial.tsx

  • Changed config import from dynamic to static require() with better
    error handling
  • Updated MCP server URL from @ngoiyaeric/mapbox-mcp-server to
    @Waldzell-Agentics/mcp-server
  • Enhanced tool description with detailed capabilities for each
    geospatial tool type
  • Improved tool selection logic to use specific tool names for different
    query types
  • Added comprehensive documentation for static image, category search,
    reverse geocoding, directions, and isochrone tools
+87/-19 

Summary by CodeRabbit

  • Documentation

    • Expanded and clarified geospatial tool descriptions with structured, multi-section guidance and sequencing notes.
  • Refactor

    • Standardized tool identifiers and streamlined tool selection, argument assembly, retry and error flows.
    • Made system prompts configurable for researcher and writer interfaces (new dynamic prompt parameter).
  • Chores

    • Adjusted configuration loading and logging behavior; updated service base URL.

@vercel
Copy link
Contributor

vercel bot commented Sep 30, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
qcx Ready Ready Preview Comment Sep 30, 2025 0:30am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 30, 2025

Walkthrough

Reworks geospatial tool loading and invocation, updates MCP server base URL, replaces tool identifiers and argument shapes, and expands geospatial prompts. Adds dynamicSystemPrompt parameters and updates system prompts in researcher, writer, and task-manager agents; no exported type declarations changed beyond function signatures.

Changes

Cohort / File(s) Summary of Changes
Geospatial tool core
lib/agents/tools/geospatial.tsx
Replaced dynamic import of Mapbox config with static require and modified config error path; updated MCP base URL to Waldzell-Agentics; changed tool-name resolution to new identifiers (directions_tool, matrix_tool, isochrone_tool, static_map_image_tool, reverse_geocode_tool, forward_geocode_tool); adjusted switch cases, argument construction, retry/timeout handling, and logging; expanded geospatialTool description text.
Researcher agent
lib/agents/researcher.tsx
Added dynamicSystemPrompt: string parameter to researcher; introduced conditional use of a dynamic system prompt; updated default system prompt to emphasize geospatial tooling and adjusted behavior guidance (don’t describe map changes); removed/commented MCP parameter usage in internal wiring.
Writer agent
lib/agents/writer.tsx
Added dynamicSystemPrompt: string parameter to writer; replaced default system prompt with expanded instructions combining search and mapbox results, strict citation/format rules, language matching and Markdown output requirements; preserves existing streaming behavior.
Task-manager agent prompt
lib/agents/task-manager.tsx
Rewrote system prompt toward geospatial/data-driven guidance; added policy/configuration keys (commitment_to_accuracy, data_driven_operations, transparency_in_uncertainty, avoidance_of_speculation, continuous_verification); expanded decision-option criteria (inquire vs proceed) and reinforced Geospatial tool usage.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Agent as Agent (researcher/writer)
  participant Resolver as Geospatial Resolver
  participant MCPClient as MCP Client
  participant MCPServer as MCP Server (Waldzell-Agentics)

  Agent->>Resolver: geospatialTool(query, params)
  Note over Resolver: Resolve to new tool IDs\ndirections_tool / matrix_tool / isochrone_tool / static_map_image_tool / reverse_geocode_tool / forward_geocode_tool
  Resolver->>Resolver: Build args per tool identifier\napply timeouts/retries
  Resolver->>MCPClient: execute(toolId, args)
  Note right of MCPClient: Base URL uses Waldzell-Agentics path
  MCPClient->>MCPServer: POST /execute (toolId, args)
  MCPServer-->>MCPClient: Result payload
  MCPClient-->>Agent: Return result (with logging/err handling)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

A hop, a map, a burrowed route I trace,
New IDs in paw, I scamper place to place.
I query, I fetch — directions and time,
Isochrones bloom where carrots chime.
With whiskered joy I log and send,
Maps stitched together — hop to the end. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title Check ❓ Inconclusive The title “prompting & MCP” is overly brief and uses generic terms without clearly summarizing the scope or intent of the changes, making it difficult to understand the primary purpose of the pull request at a glance. Please revise the title to a concise sentence that highlights the main enhancement, for example “Enhance geospatial prompting and update MCP server configuration,” so that reviewers immediately grasp the core change.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch Prompting

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🧪 Early access (Sonnet 4.5): enabled

We are currently testing the Sonnet 4.5 model, which is expected to improve code review quality. However, this model may lead to increased noise levels in the review comments. Please disable the early access features if the noise level causes any inconvenience.

Note:

  • Public repositories are always opted into early access features.
  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.

Comment @coderabbitai help to get the list of available commands and usage tips.

@charliecreates
Copy link

  1. The PR combines two unrelated changes: prompting fixes and MCP programming updates. Consider splitting into focused PRs for better clarity and reviewability.
  2. The removal of package-lock.json can cause dependency inconsistencies and should be justified. If intentionally deleting the lock file, please provide context in the description.
  3. Changes in lib/agents/tools/geospatial.tsx are not described in detail. A summary of what's fixed in prompting and what changes were made to MCP is needed for effective review.
  4. Ensure any code changes are covered by tests and that all tests pass after these changes.
  5. If MCP programming involves logic or business-critical changes, add comments or documentation highlighting the modifications.

Please address the above for a smoother review process.

@qodo-code-review
Copy link
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Possible Issue

The static require path for mapbox_mcp_config.json is relative and may break at runtime depending on bundler/TS transpilation and execution cwd. Validate that require('../../../mapbox_mcp_config.json') resolves correctly in all environments (dev, prod, serverless).

  mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
  config = { ...mapboxMcpConfig, mapboxAccessToken };
  console.log('[GeospatialTool] Config loaded successfully');
} catch (configError: any) {
  throw configError;
}
Tool Mapping

The new tool selection names (e.g., directions_tool, matrix_tool, static_map_image_tool) must match the MCP server’s advertised tools. Verify listTools() actually returns these names; otherwise queries like 'directions' or 'map' will fail silently with undefined toolName.

switch (queryType) {
  case 'directions': return prefer('directions_tool') 
  case 'distance': return prefer('matrix_tool');
  case 'search': return prefer( 'isochrone_tool','category_search_tool') || 'poi_search_tool';
  case 'map': return prefer('static_map_image_tool') 
  case 'reverse': return prefer('reverse_geocode_tool');
  case 'geocode': return prefer('forward_geocode_tool');
}
Argument Shape

The 'directions' case now sends { waypoints: [origin, destination], profile: params.mode }. Confirm the MCP directions tool expects waypoints and profile keys and the waypoint coordinate format; previously distance used { places: [...] }, so schemas may differ.

  case 'directions': return { waypoints: [params.origin, params.destination], includeMapPreview: includeMap, profile: params.mode };
  case 'distance': return { places: [params.origin, params.destination], includeMapPreview: includeMap, mode: params.mode || 'driving' };
  case 'reverse': return { searchText: `${params.coordinates.latitude},${params.coordinates.longitude}`, includeMapPreview: includeMap, maxResults: params.maxResults || 5 };
  case 'search': return { searchText: params.query, includeMapPreview: includeMap, maxResults: params.maxResults || 5, ...(params.coordinates && { proximity: `${params.coordinates.latitude},${params.coordinates.longitude}` }), ...(params.radius && { radius: params.radius }) };
  case 'geocode': 
  case 'map': return { searchText: params.location, includeMapPreview: includeMap, maxResults: queryType === 'geocode' ? params.maxResults || 5 : undefined };
}

@qodo-code-review
Copy link
Contributor

qodo-code-review bot commented Sep 30, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Split the monolithic tool into multiple tools

Refactor the single geospatialTool into multiple, distinct tools like
directionsTool and isochroneTool. This improves model efficiency and follows
standard agentic system design by providing concise, specific tools instead of
one monolithic tool with a long description.

Examples:

lib/agents/tools/geospatial.tsx [150-272]
export const geospatialTool = ({ uiStream }: { uiStream: ReturnType<typeof createStreamableUI> }) => ({
  description: `Use this tool for location-based queries including: 
  There a plethora of tools inside this tool accessible on the mapbox mcp server where switch case into the tool of choice for that use case
  If the Query is supposed to use multiple tools in a sequence you must access all the tools in the sequence and then provide a final answer based on the results of all the tools used. 

Static image tool:

Generates static map images using the Mapbox static image API. Features include:

Custom map styles (streets, outdoors, satellite, etc.)

 ... (clipped 113 lines)

Solution Walkthrough:

Before:

export const geospatialTool = ({ uiStream }) => ({
  description: `Use this tool for location-based queries including: 
  ... (very long description of multiple sub-tools) ...
  Static image tool: ...
  Category search tool: ...
  Directions tool: ...
  Isochrone tool: ...`,
  parameters: geospatialQuerySchema, // a schema with 'queryType'
  execute: async (params) => {
    const { queryType } = params;
    const toolName = (() => {
      switch (queryType) {
        case 'directions': return 'directions_tool';
        case 'search': return 'category_search_tool';
        // ... other cases
      }
    })();
    // ... run toolName with args
  }
});

After:

export const directionsTool = {
  description: "Fetches routing directions using the Mapbox Directions API for various profiles (driving, walking, cycling).",
  parameters: directionsSchema, // specific schema
  execute: async (params) => {
    // ... connect and call 'directions_tool' on MCP server
  }
};

export const isochroneTool = {
  description: "Computes areas reachable within a specified time from a location.",
  parameters: isochroneSchema, // specific schema
  execute: async (params) => {
    // ... connect and call 'isochrone_tool' on MCP server
  }
};

// ... other distinct tools like staticMapTool, reverseGeocodeTool, etc.
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a major architectural anti-pattern introduced in the PR, where a single tool has an excessively long description and complex internal routing, which is inefficient for the model and hard to maintain.

High
Possible issue
Fix incorrect parameter for geocoding

Separate the geocode and map cases in the toolArgs switch statement, using
params.query for geocode and params.location for map to pass the correct
parameters.

lib/agents/tools/geospatial.tsx [269-270]

-case 'geocode': 
-case 'map': return { searchText: params.location, includeMapPreview: includeMap, maxResults: queryType === 'geocode' ? params.maxResults || 5 : undefined };
+case 'geocode': return { searchText: params.query, includeMapPreview: includeMap, maxResults: params.maxResults || 5 };
+case 'map': return { searchText: params.location, includeMapPreview: includeMap };
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a bug where the geocode case incorrectly uses params.location instead of params.query due to a fall-through, which would break the geocoding functionality.

High
Add fallbacks for tool selection

Add fallback values for each case in the toolName selection switch statement to
prevent potential runtime errors if the prefer function returns undefined.

lib/agents/tools/geospatial.tsx [252-259]

 switch (queryType) {
-  case 'directions': return prefer('directions_tool') 
-  case 'distance': return prefer('matrix_tool');
+  case 'directions': return prefer('directions_tool') || 'directions_tool';
+  case 'distance': return prefer('matrix_tool') || 'matrix_tool';
   case 'search': return prefer( 'isochrone_tool','category_search_tool') || 'poi_search_tool';
-  case 'map': return prefer('static_map_image_tool') 
-  case 'reverse': return prefer('reverse_geocode_tool');
-  case 'geocode': return prefer('forward_geocode_tool');
+  case 'map': return prefer('static_map_image_tool') || 'static_map_image_tool';
+  case 'reverse': return prefer('reverse_geocode_tool') || 'reverse_geocode_tool';
+  case 'geocode': return prefer('forward_geocode_tool') || 'forward_geocode_tool';
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out a potential runtime error if prefer returns undefined and improves code robustness by adding fallback tool names, preventing crashes if a tool is not found.

Medium
General
Simplify redundant try-catch block

Remove the redundant nested try...catch block around the require() call, as the
outer catch block already handles any potential errors.

lib/agents/tools/geospatial.tsx [55-63]

 // Use static import for config
-let mapboxMcpConfig;
-try {
-  mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
-  config = { ...mapboxMcpConfig, mapboxAccessToken };
-  console.log('[GeospatialTool] Config loaded successfully');
-} catch (configError: any) {
-  throw configError;
-}
+const mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
+config = { ...mapboxMcpConfig, mapboxAccessToken };
+console.log('[GeospatialTool] Config loaded successfully');
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies a redundant try...catch block and proposes a simplification that improves code readability without changing the logic.

Low
  • Update

Copy link
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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/agents/tools/geospatial.tsx (1)

247-260: Add error handling for missing tool names.

The tool name resolution logic can return undefined if the preferred tool is not found in the MCP server's tool list. Cases like 'directions', 'map', 'reverse', and 'geocode' (lines 253, 256-258) have no fallback, and there's no default case for unexpected queryType values. This will cause mcpClient.callTool on line 283 to fail with an unclear error.

Add validation after tool name resolution:

         switch (queryType) {
           case 'directions': return prefer('directions_tool') 
           case 'distance': return prefer('matrix_tool');
           case 'search': return prefer( 'isochrone_tool','category_search_tool') || 'poi_search_tool';
           case 'map': return prefer('static_map_image_tool') 
           case 'reverse': return prefer('reverse_geocode_tool');
           case 'geocode': return prefer('forward_geocode_tool');
+          default: return undefined;
         }
       })();
+
+      if (!toolName) {
+        throw new Error(`No suitable tool found for query type: ${queryType}`);
+      }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f88d3ce and 1103e01.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • lib/agents/tools/geospatial.tsx (4 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
lib/agents/tools/geospatial.tsx (2)
mapbox_mcp/index.ts (1)
  • testMCPConnection (14-89)
components/map/map-query-handler.tsx (2)
  • GeospatialToolOutput (18-23)
  • toolOutput (33-74)
🔇 Additional comments (3)
lib/agents/tools/geospatial.tsx (3)

263-272: Schema definitions align with toolArgs parameter usage
geospatialQuerySchema’s discriminated union explicitly defines origin, destination, mode, query, coordinates, radius, location, maxResults, and includeMap for each respective queryType, matching all fields accessed in toolArgs.


253-259: Verify and align geospatial tool identifiers with the MCP server
The names used in lib/agents/tools/geospatial.tsx (directions_tool, matrix_tool, isochrone_tool, category_search_tool, poi_search_tool, static_map_image_tool, reverse_geocode_tool, forward_geocode_tool) aren’t present in the MCP server hooks (only geocode_location is documented). Confirm the exact tool names exposed by @Waldzell-Agentics/mcp-server (formerly @ngoiyaeric/mapbox-mcp-server) and update these mappings—or add a startup validation—to prevent runtime failures.


72-75: Confirm createSmitheryUrl usage to prevent duplicate query parameters.
The URL on line 72 already includes api_key and profile; ensure that calling createSmitheryUrl(mcpServerBaseUrl, smitheryUrlOptions) won’t re-append or conflict with these query parameters.

Comment on lines +55 to +63
// Use static import for config
let mapboxMcpConfig;
try {
mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
config = { ...mapboxMcpConfig, mapboxAccessToken };
console.log('[GeospatialTool] Config loaded successfully');
} catch (configError: any) {
throw configError;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Remove redundant nested try-catch block.

The inner try-catch (lines 57-63) immediately re-throws the caught error without any transformation or additional handling. This adds unnecessary nesting without providing value. The outer catch block (lines 64-68) already handles config loading failures with appropriate fallback logic.

Apply this diff to simplify the error handling:

-  // Load config from file or fallback
-  let config;
-  try {
-    // Use static import for config
-    let mapboxMcpConfig;
-    try {
-      mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
-      config = { ...mapboxMcpConfig, mapboxAccessToken };
-      console.log('[GeospatialTool] Config loaded successfully');
-    } catch (configError: any) {
-      throw configError;
-    }
+  // Load config from file or fallback
+  let config;
+  try {
+    const mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
+    config = { ...mapboxMcpConfig, mapboxAccessToken };
+    console.log('[GeospatialTool] Config loaded successfully');
   } catch (configError: any) {
     console.error('[GeospatialTool] Failed to load mapbox config:', configError.message);
     config = { mapboxAccessToken, version: '1.0.0', name: 'mapbox-mcp-server' };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Use static import for config
let mapboxMcpConfig;
try {
mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
config = { ...mapboxMcpConfig, mapboxAccessToken };
console.log('[GeospatialTool] Config loaded successfully');
} catch (configError: any) {
throw configError;
}
// Load config from file or fallback
let config;
try {
const mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
config = { ...mapboxMcpConfig, mapboxAccessToken };
console.log('[GeospatialTool] Config loaded successfully');
} catch (configError: any) {
console.error('[GeospatialTool] Failed to load mapbox config:', configError.message);
config = { mapboxAccessToken, version: '1.0.0', name: 'mapbox-mcp-server' };
}
🤖 Prompt for AI Agents
In lib/agents/tools/geospatial.tsx around lines 55 to 63, remove the redundant
inner try-catch that simply re-throws the caught error; instead perform the
require(...) and config assignment directly (letting the outer catch handle
failures). Ensure no behavior changes: keep the console.log on success and rely
on the existing outer catch block for fallback/error handling.

Comment on lines +151 to +218
description: `Use this tool for location-based queries including:
There a plethora of tools inside this tool accessible on the mapbox mcp server where switch case into the tool of choice for that use case
If the Query is supposed to use multiple tools in a sequence you must access all the tools in the sequence and then provide a final answer based on the results of all the tools used.

Static image tool:

Generates static map images using the Mapbox static image API. Features include:

Custom map styles (streets, outdoors, satellite, etc.)
Adjustable image dimensions and zoom levels
Support for multiple markers with custom colors and labels
Overlay options including polylines and polygons
Auto-fitting to specified coordinates

Category search tool:

Performs a category search using the Mapbox Search Box category search API. Features include:
Search for points of interest by category (restaurants, hotels, gas stations, etc.)
Filtering by geographic proximity
Customizable result limits
Rich metadata for each result
Support for multiple languages

Reverse geocoding tool:

Performs reverse geocoding using the Mapbox geocoding V6 API. Features include:
Convert geographic coordinates to human-readable addresses
Customizable levels of detail (street, neighborhood, city, etc.)
Results filtering by type (address, poi, neighborhood, etc.)
Support for multiple languages
Rich location context information

Directions tool:

Fetches routing directions using the Mapbox Directions API. Features include:

Support for different routing profiles: driving (with live traffic or typical), walking, and cycling
Route from multiple waypoints (2-25 coordinate pairs)
Alternative routes option
Route annotations (distance, duration, speed, congestion)

Scheduling options:

Future departure time (depart_at) for driving and driving-traffic profiles
Desired arrival time (arrive_by) for driving profile only
Profile-specific optimizations:
Driving: vehicle dimension constraints (height, width, weight)
Exclusion options for routing:
Common exclusions: ferry routes, cash-only tolls
Driving-specific exclusions: tolls, motorways, unpaved roads, tunnels, country borders, state borders
Custom point exclusions (up to 50 geographic points to avoid)
GeoJSON geometry output format

Isochrone tool:

Computes areas that are reachable within a specified amount of times from a location using Mapbox Isochrone API. Features include:

Support for different travel profiles (driving, walking, cycling)
Customizable travel times or distances
Multiple contour generation (e.g., 15, 30, 45 minute ranges)
Optional departure or arrival time specification
Color customization for visualization

Search and geocode tool:
Uses the Mapbox Search Box Text Search API endpoint to power searching for and geocoding POIs, addresses, places, and any other types supported by that API. This tool consolidates the functionality that was previously provided by the ForwardGeocodeTool and PoiSearchTool (from earlier versions of this MCP server) into a single tool.`


,
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Consider restructuring the tool description for clarity.

The description has expanded from a concise statement to 65+ lines of prose covering multiple distinct tools (static image, category search, reverse geocoding, directions, isochrone, search/geocode). While comprehensive, this format may:

  1. Consume significant tokens in LLM context windows
  2. Make it harder for the AI to quickly identify the appropriate tool for a given query
  3. Conflate multiple tool capabilities into one description

Consider using structured markdown (bullet points, clear sections) or a more concise summary with references to detailed documentation.

🤖 Prompt for AI Agents
In lib/agents/tools/geospatial.tsx around lines 151 to 218 the tool description
has grown into a 65+ line prose block that mixes many distinct sub-tools and
will bloat LLM context and reduce clarity; replace this long paragraph with a
concise, structured summary that lists each sub-tool as a one-line entry (name +
2–3 key capabilities) or a short bulleted list and add a single-line pointer/URL
to full docs for details, ensuring each sub-tool is clearly separable so the
agent can select the correct capability without scanning long prose.

Copy link
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: 8

♻️ Duplicate comments (3)
lib/agents/tools/geospatial.tsx (3)

55-63: Remove redundant nested try-catch block.

The inner try-catch immediately re-throws without transformation. This was flagged in a previous review and remains unaddressed.

Apply the previously suggested diff to simplify:

-  // Load config from file or fallback
-  let config;
-  try {
-    // Use static import for config
-    let mapboxMcpConfig;
-    try {
-      mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
-      config = { ...mapboxMcpConfig, mapboxAccessToken };
-      console.log('[GeospatialTool] Config loaded successfully');
-    } catch (configError: any) {
-      throw configError;
-    }
+  // Load config from file or fallback
+  let config;
+  try {
+    const mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
+    config = { ...mapboxMcpConfig, mapboxAccessToken };
+    console.log('[GeospatialTool] Config loaded successfully');
   } catch (configError: any) {
     console.error('[GeospatialTool] Failed to load mapbox config:', configError.message);
     config = { mapboxAccessToken, version: '1.0.0', name: 'mapbox-mcp-server' };

151-218: Consider restructuring the tool description for clarity.

This 65+ line prose block was flagged in a previous review for consuming excessive tokens and making tool selection harder. The issue remains unaddressed.


152-152: Fix grammatical error.

The phrase "There a plethora" is missing the verb "is". This was flagged in a previous review and remains unfixed.

Apply this diff:

-  There a plethora of tools inside this tool accessible on the mapbox mcp server where switch case into the tool of choice for that use case
+  There is a plethora of tools inside this tool accessible on the mapbox mcp server where we switch case into the tool of choice for that use case
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1103e01 and f8bd433.

📒 Files selected for processing (4)
  • lib/agents/researcher.tsx (1 hunks)
  • lib/agents/task-manager.tsx (1 hunks)
  • lib/agents/tools/geospatial.tsx (5 hunks)
  • lib/agents/writer.tsx (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
lib/agents/writer.tsx (3)
components/settings/components/system-prompt-form.tsx (1)
  • SystemPromptForm (9-36)
lib/actions/chat.ts (2)
  • saveSystemPrompt (218-237)
  • getSystemPrompt (239-254)
components/settings/components/settings.tsx (2)
  • fetchPrompt (81-86)
  • fetchPrompt (80-88)
🔇 Additional comments (9)
lib/agents/tools/geospatial.tsx (2)

72-72: LGTM: MCP server URL updated as intended.

The migration from @ngoiyaeric/mapbox-mcp-server to @Waldzell-Agentics/mcp-server aligns with the PR objectives.


265-265: LGTM: Directions tool arguments updated correctly.

The waypoints array and profile parameter align with typical routing API expectations.

lib/agents/researcher.tsx (2)

14-21: LGTM: Dynamic system prompt parameter added.

The new dynamicSystemPrompt parameter provides valuable flexibility for customizing the researcher's behavior at call sites.


47-66: LGTM: Comprehensive geospatial tool guidance.

The expanded examples and structured categories (Location Discovery, Navigation & Travel, Visualization & Maps, Analysis & Planning) provide clear guidance for when to invoke the geospatial tool.

lib/agents/task-manager.tsx (2)

12-16: LGTM: Policy keys enhance transparency and accuracy.

The addition of explicit policy commitments (accuracy, data-driven operations, uncertainty transparency, avoiding speculation, continuous verification) strengthens the system's reliability guarantees.


18-22: LGTM: Enhanced location query guidance.

The detailed instructions for location-based queries (addresses, travel method, time constraints, output formats) improve the task manager's ability to gather necessary details before proceeding.

lib/agents/writer.tsx (3)

7-8: LGTM! Dynamic system prompt parameter added.

The addition of the dynamicSystemPrompt parameter allows runtime customization of the system prompt, which aligns with the user settings functionality shown in the relevant code snippets.


22-27: LGTM! Enhanced system prompt with comprehensive guidance.

The updated default system prompt properly integrates mapbox results with search results, enforces citation requirements, language matching, and proper Markdown formatting. This provides clear instructions for the AI agent.


32-32: LGTM! Proper fallback logic for system prompt selection.

The ternary operator correctly prioritizes the dynamic system prompt when provided and falls back to the default prompt otherwise.

Current date and time: ${currentDate}. When tools are not needed, provide direct, helpful answers based on your knowledge.Match the language of your response to the user's language.
Always aim to directly address the user's question. If using information from a tool (like web search), cite the source URL.

There are also some proconfigured example queires.
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix typographical errors.

Line 36 contains two typos: "proconfigured" should be "preconfigured" and "queires" should be "queries".

Apply this diff:

-There are also some proconfigured example queires.
+There are also some preconfigured example queries.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
There are also some proconfigured example queires.
There are also some preconfigured example queries.
🤖 Prompt for AI Agents
In lib/agents/researcher.tsx around line 36, fix the typos in the sentence:
replace "proconfigured" with "preconfigured" and "queires" with "queries" so the
line reads with correct spelling.

Comment on lines +37 to +40
When asked the following respond accordingly:
'What is a planet computer?' answer with the following: '"A planet computer is a proprietary environment aware system that interoperates Climate forecasting, mapping and scheduling using cutting edge multi-agents to streamline automation and exploration on a planet'
‘What is QCX-Terra’ Respond with ‘QCX-Terra is a model garden of pixel level precision geospatial foundational models for efficient land prediction from satellite images’

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Consider restructuring hardcoded example queries.

The hardcoded question-answer pairs for "planet computer" and "QCX-Terra" would be clearer as a structured list or lookup table rather than inline prose instructions.

Example:

Predefined Examples:
- "What is a planet computer?"  "A planet computer is a proprietary environment aware system..."
- "What is QCX-Terra?"  "QCX-Terra is a model garden of pixel level precision..."
🤖 Prompt for AI Agents
In lib/agents/researcher.tsx around lines 37-40, the hardcoded example Q/A prose
should be refactored into a structured lookup: create a typed constant (e.g.,
PREDEFINED_EXAMPLES: Record<string,string> or an array of {question,answer})
containing the two pairs ("What is a planet computer?" -> "A planet computer is
a proprietary environment aware system..." and "What is QCX-Terra?" ->
"QCX-Terra is a model garden of pixel level precision..."), replace the inline
prose with code that reads from that lookup when composing responses, and export
or scope the constant appropriately so tests and other modules can reuse it;
maintain original exact answer strings and remove duplicated quotes or smart
quotes.

const result = await generateObject({
model: getModel() as LanguageModel,
system: `As a professional web researcher, your primary objective is to fully comprehend the user's query, conduct thorough web searches to gather the necessary information, and provide an appropriate response.
system: `As a planet computer, your primary objective is to fully comprehend the user's query, conduct thorough web searches and use Geospatial tools to gather preview the necessary information, and provide an appropriate response.
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix grammatical error.

The phrase "gather preview the necessary information" is malformed. It should be "gather or preview" or "gather and preview".

Apply this diff:

-system: `As a planet computer, your primary objective is to fully comprehend the user's query, conduct thorough web searches and use Geospatial tools to gather preview the necessary information, and provide an appropriate response.
+system: `As a planet computer, your primary objective is to fully comprehend the user's query, conduct thorough web searches and use Geospatial tools to gather or preview the necessary information, and provide an appropriate response.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
system: `As a planet computer, your primary objective is to fully comprehend the user's query, conduct thorough web searches and use Geospatial tools to gather preview the necessary information, and provide an appropriate response.
system: `As a planet computer, your primary objective is to fully comprehend the user's query, conduct thorough web searches and use Geospatial tools to gather or preview the necessary information, and provide an appropriate response.
🤖 Prompt for AI Agents
In lib/agents/task-manager.tsx around line 10, the system prompt contains a
malformed phrase "gather preview the necessary information"; replace that
fragment with a correct conjunction such as "gather or preview the necessary
information" (or "gather and preview the necessary information") so the sentence
reads grammatically correct and preserves the intended meaning.

Ask for specific output formats when needed ("as a map image", "in JSON format")
Your decision should be based on a careful assessment of the context, location and the potential for further information to improve the quality and relevance of your response. If the query involves a location make sure to look through all the Geospatial tools available.
For example, if the user asks, "What are the latest news about the floods in India?", you may choose to "proceed" as the query is clear and can be answered effectively with web research alone.
However, if the user asks, "What's the warmest temperature in my area?", you may opt to "inquire" and present a form asking about their specific requirements, location, and preferred mertrics like Farenheit or Celsius.
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix typographical errors.

Line 24 contains two typos: "mertrics" should be "metrics" and "Farenheit" should be "Fahrenheit".

Apply this diff:

-However, if the user asks, "What's the warmest temperature in my area?", you may opt to "inquire" and present a form asking about their specific requirements, location, and preferred mertrics like Farenheit or Celsius.
+However, if the user asks, "What's the warmest temperature in my area?", you may opt to "inquire" and present a form asking about their specific requirements, location, and preferred metrics like Fahrenheit or Celsius.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
However, if the user asks, "What's the warmest temperature in my area?", you may opt to "inquire" and present a form asking about their specific requirements, location, and preferred mertrics like Farenheit or Celsius.
However, if the user asks, "What's the warmest temperature in my area?", you may opt to "inquire" and present a form asking about their specific requirements, location, and preferred metrics like Fahrenheit or Celsius.
🤖 Prompt for AI Agents
In lib/agents/task-manager.tsx around line 24, there's a sentence with two
typos: replace "mertrics" with "metrics" and "Farenheit" with "Fahrenheit";
update the text accordingly so the sentence reads "...preferred metrics like
Fahrenheit or Celsius."

case 'geocode': return prefer('geocode_location', 'mapbox_geocoding') || 'mapbox_geocoding';
case 'directions': return prefer('directions_tool')
case 'distance': return prefer('matrix_tool');
case 'search': return prefer( 'isochrone_tool','category_search_tool') || 'poi_search_tool';
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Questionable tool selection for search queries.

The search case prefers isochrone_tool first, but isochrone tools compute reachable areas (travel-time polygons), not search results. This will route search queries to the wrong tool if isochrone_tool exists.

Apply this diff to prioritize appropriate tools:

-          case 'search': return prefer( 'isochrone_tool','category_search_tool') || 'poi_search_tool';
+          case 'search': return prefer('category_search_tool', 'poi_search_tool');

If isochrone functionality is needed, introduce a separate queryType (e.g., 'isochrone' or 'reachability') rather than conflating it with search.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
case 'search': return prefer( 'isochrone_tool','category_search_tool') || 'poi_search_tool';
case 'search': return prefer('category_search_tool', 'poi_search_tool');
🤖 Prompt for AI Agents
In lib/agents/tools/geospatial.tsx around line 255, the 'search' case currently
prefers 'isochrone_tool' which is incorrect because isochrone computes reachable
areas rather than search results; change the preference order to prefer
search-related tools first (e.g.,
prefer('category_search_tool','poi_search_tool') || 'poi_search_tool') so search
queries route to appropriate tools, and if isochrone functionality is needed add
a new queryType like 'isochrone' or 'reachability' and handle that separately
instead of including it in the 'search' branch.

try {
toolCallResult = await Promise.race([
mcpClient.callTool({ name: toolName, arguments: toolArgs }),
mcpClient.callTool({ name: toolName ?? 'unknown_tool', arguments: toolArgs }),
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Consider failing fast if toolName is undefined.

The fallback toolName ?? 'unknown_tool' prevents a null reference but will likely result in a failed tool call. Consider validating toolName before the retry loop and throwing a descriptive error early.

Example:

if (!toolName) {
  throw new Error(`No appropriate tool found for queryType: ${queryType}`);
}
🤖 Prompt for AI Agents
In lib/agents/tools/geospatial.tsx around line 283, the code uses a fallback
'unknown_tool' when toolName is undefined which will likely cause a failing tool
call; instead validate toolName before entering the retry loop and throw a
descriptive error (e.g., throw new Error(`No appropriate tool found for
queryType: ${queryType}`)) so the function fails fast, and remove the fallback
usage at the mcpClient.callTool invocation.

Link format: [link text](url)
Image format: ![alt text](url)

There are also some proconfigured example queires.
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix typos in the system prompt.

Line 28 contains two typos:

  • "proconfigured" should be "preconfigured"
  • "queires" should be "queries"

Apply this diff:

-    There are also some proconfigured example queires. 
+    There are also some preconfigured example queries.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
There are also some proconfigured example queires.
There are also some preconfigured example queries.
🤖 Prompt for AI Agents
In lib/agents/writer.tsx around line 28, fix typos in the system prompt: replace
"proconfigured" with "preconfigured" and "queires" with "queries" so the
sentence reads correctly (e.g., "There are also some preconfigured example
queries.").

Image format: ![alt text](url)

There are also some proconfigured example queires.
When asked about 'What is a planet computer?' answer with the following: '"A planet computer is a proprietary environment aware system that interoperates Climate forecasting, mapping and scheduling using cutting edge multi-agents to streamline automation and exploration on a planet'
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Fix syntax error and improve hardcoded example.

Line 29 has multiple issues:

  1. Critical: Missing closing double quote at the end of the string, which will cause a syntax error
  2. The hardcoded answer has grammatical issues: "interoperates Climate forecasting" should be "integrates climate forecasting"
  3. Hardcoding specific examples in the system prompt is poor practice—consider moving to a separate configuration file or examples database

Apply this diff to fix the immediate syntax error and grammar:

-    When asked about 'What is a planet computer?' answer with the following: '"A planet computer is a proprietary environment aware system that interoperates Climate forecasting, mapping and scheduling using cutting edge multi-agents to streamline automation and exploration on a planet'
+    When asked about 'What is a planet computer?' answer with the following: "A planet computer is a proprietary environment-aware system that integrates climate forecasting, mapping and scheduling using cutting-edge multi-agents to streamline automation and exploration on a planet."

Recommended refactor: Consider extracting hardcoded examples into a separate configuration file or database to improve maintainability.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
When asked about 'What is a planet computer?' answer with the following: '"A planet computer is a proprietary environment aware system that interoperates Climate forecasting, mapping and scheduling using cutting edge multi-agents to streamline automation and exploration on a planet'
When asked about 'What is a planet computer?' answer with the following: "A planet computer is a proprietary environment-aware system that integrates climate forecasting, mapping and scheduling using cutting-edge multi-agents to streamline automation and exploration on a planet."
🤖 Prompt for AI Agents
In lib/agents/writer.tsx around line 29, the string for the example response is
missing a closing double-quote (causing a syntax error) and contains grammar
issues; fix by closing the string, replace "interoperates Climate forecasting"
with "integrates climate forecasting" and correct capitalization/punctuation as
needed, and as a follow-up move this hardcoded example into a separate config or
examples file (or load from an examples DB) rather than keeping it inline.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant