Skip to content

Commit 1b6d0e1

Browse files
authored
Merge pull request #304 from QueueLab/Prompting
prompting & MCP
2 parents ccd1a2c + f8bd433 commit 1b6d0e1

File tree

5 files changed

+135
-18292
lines changed

5 files changed

+135
-18292
lines changed

lib/agents/researcher.tsx

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,23 +29,42 @@ export async function researcher(
2929

3030
const currentDate = new Date().toLocaleString()
3131
// Default system prompt, used if dynamicSystemPrompt is not provided
32-
const default_system_prompt = `As a comprehensive AI assistant, you can search the web, retrieve information from URLs, and understand geospatial queries to assist the user and display information on a map.
33-
Current date and time: ${currentDate}.
32+
const default_system_prompt = `As a comprehensive AI assistant, you can search the web, retrieve information from URLs except from maps -here use the Geospatial tools provided, and understand geospatial queries to assist the user and display information on a map.
33+
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.
34+
Always aim to directly address the user's question. If using information from a tool (like web search), cite the source URL.
35+
36+
There are also some proconfigured example queires.
37+
When asked the following respond accordingly:
38+
'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'
39+
‘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’
40+
3441
3542
Tool Usage Guide:
43+
3644
- For general web searches for factual information: Use the 'search' tool.
3745
- For retrieving content from specific URLs provided by the user: Use the 'retrieve' tool. (Do not use this for URLs found in search results).
38-
- **For any questions involving locations, places, addresses, geographical features, finding businesses or points of interest, distances between locations, or directions: You MUST use the 'geospatialQueryTool'. This tool will process the query, and relevant information will often be displayed or updated on the user's map automatically.**
46+
47+
- For any questions involving locations, places, addresses, geographical features, finding businesses or points of interest, distances between locations, or directions: You MUST use the 'geospatialQueryTool'. This tool will process the query, and relevant information will often be displayed or updated on the user's map automatically.**
3948
Examples of queries for 'geospatialQueryTool':
40-
- "Where is the Louvre Museum?"
41-
- "Show me cafes near the current map center."
42-
- "How far is it from New York City to Los Angeles?"
43-
- "What are some parks in San Francisco?"
44-
When you use 'geospatialQueryTool', you don't need to describe how the map will change; simply provide your textual answer based on the query, and trust the map will update appropriately.
49+
Location Discovery
50+
"Find coffee shops within walking distance of the Empire State Building"
51+
"Show me gas stations along the route from Boston to New York"
52+
"What restaurants are near Times Square?"
53+
Navigation & Travel
54+
"Get driving directions from LAX to Hollywood with current traffic"
55+
"How long would it take to walk from Central Park to Times Square?"
56+
"Calculate travel time from my hotel (Four Seasons) to JFK Airport by taxi during rush hour"
57+
Visualization & Maps
58+
"Create a map image showing the route from Golden Gate Bridge to Fisherman's Wharf with markers at both locations"
59+
"Show me a satellite view of Manhattan with key landmarks marked"
60+
"Generate a map highlighting all Starbucks locations within a mile of downtown Seattle"
61+
Analysis & Planning
62+
"Show me areas reachable within 30 minutes of downtown Portland by car"
63+
"Calculate a travel time matrix between these 3 hotel locations (Marriott, Sheraton and Hilton) and the convention center in Denver"
64+
"Find the optimal route visiting these 3 tourist attractions (Golden Gate, Musical Stairs and Fisherman's Wharf) in San Francisco"
4565
46-
When tools are not needed, provide direct, helpful answers based on your knowledge.
47-
Always aim to directly address the user's question. If using information from a tool (like web search), cite the source URL.
48-
Match the language of your response to the user's language.`;
66+
When you use 'geospatialQueryTool', you don't need to describe how the map will change; simply provide your textual answer based on the query, and trust the map will update appropriately.
67+
`;
4968

5069
const systemToUse = dynamicSystemPrompt && dynamicSystemPrompt.trim() !== '' ? dynamicSystemPrompt : default_system_prompt;
5170

lib/agents/task-manager.tsx

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,21 @@ export async function taskManager(messages: CoreMessage[]) {
77
try {
88
const result = await generateObject({
99
model: getModel() as LanguageModel,
10-
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.
10+
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.
1111
To achieve this, you must first analyze the user's input and determine the optimal course of action. You have two options at your disposal:
12+
"commitment_to_accuracy": "All analyses, decisions, and communications must be grounded in the most accurate available data. Prioritize verifiable information and clearly distinguish between observed facts, derived inferences, and predictive models.",
13+
"data_driven_operations": "Base all operational procedures, exploration strategies, and automated tasks on empirical evidence and validated data inputs. Assumptions made due to incomplete data must be explicitly stated.",
14+
"transparency_in_uncertainty": "When faced with ambiguity, incomplete data, or conflicting information, explicitly state the level of uncertainty. Quantify confidence where possible and clearly articulate potential impacts of this uncertainty on conclusions or actions.",
15+
"avoidance_of_speculation": "Generate responses and take actions based on known information. Do not invent, fabricate, or present unsubstantiated claims as facts. If information is unavailable, state so clearly.",
16+
"continuous_verification": "Wherever feasible, cross-verify information from multiple sources or sensors. Implement checks to ensure data integrity throughout processing and decision-making cycles."
1217
1. "proceed": If the provided information is sufficient to address the query effectively, choose this option to proceed with the research and formulate a response.
13-
2. "inquire": If you believe that additional information from the user would enhance your ability to provide a comprehensive response, select this option. You may present a form to the user, offering default selections or free-form input fields, to gather the required details.
14-
Your decision should be based on a careful assessment of the context and the potential for further information to improve the quality and relevance of your response.
15-
For example, if the user asks, "What are the key features of the latest iPhone model?", you may choose to "proceed" as the query is clear and can be answered effectively with web research alone.
16-
However, if the user asks, "What's the best smartphone for my needs?", you may opt to "inquire" and present a form asking about their specific requirements, budget, and preferred features to provide a more tailored recommendation.
18+
2. "inquire": If you believe that additional information from the user would enhance your ability to provide a comprehensive response, select this option. You may present a form to the user, offering default selections or free-form input fields, to gather the required details.if its a location based query clarify the following detailsBe specific about locations (use full addresses or landmark names)
19+
Specify your preferred travel method (driving, walking, cycling)
20+
Include time constraints when relevant ("during rush hour", "at 3 PM")
21+
Ask for specific output formats when needed ("as a map image", "in JSON format")
22+
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.
23+
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.
24+
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.
1725
Make your choice wisely to ensure that you fulfill your mission as a web researcher effectively and deliver the most valuable assistance to the user.
1826
`,
1927
messages,

lib/agents/tools/geospatial.tsx

Lines changed: 88 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,15 @@ async function getConnectedMcpClient(): Promise<McpClient | null> {
5252
// Load config from file or fallback
5353
let config;
5454
try {
55-
const mapboxMcpConfig = await import('QCX/mapbox_mcp_config.json');
56-
config = { ...mapboxMcpConfig.default || mapboxMcpConfig, mapboxAccessToken };
57-
console.log('[GeospatialTool] Config loaded successfully');
55+
// Use static import for config
56+
let mapboxMcpConfig;
57+
try {
58+
mapboxMcpConfig = require('../../../mapbox_mcp_config.json');
59+
config = { ...mapboxMcpConfig, mapboxAccessToken };
60+
console.log('[GeospatialTool] Config loaded successfully');
61+
} catch (configError: any) {
62+
throw configError;
63+
}
5864
} catch (configError: any) {
5965
console.error('[GeospatialTool] Failed to load mapbox config:', configError.message);
6066
config = { mapboxAccessToken, version: '1.0.0', name: 'mapbox-mcp-server' };
@@ -63,7 +69,7 @@ async function getConnectedMcpClient(): Promise<McpClient | null> {
6369

6470
// Build Smithery URL
6571
const smitheryUrlOptions = { config, apiKey, profileId };
66-
const mcpServerBaseUrl = `https://server.smithery.ai/@ngoiyaeric/mapbox-mcp-server/mcp?api_key=${smitheryUrlOptions.apiKey}&profile=${smitheryUrlOptions.profileId}`;
72+
const mcpServerBaseUrl = `https://server.smithery.ai/@Waldzell-Agentics/mcp-server/mcp?api_key=${smitheryUrlOptions.apiKey}&profile=${smitheryUrlOptions.profileId}`;
6773
let serverUrlToUse;
6874
try {
6975
serverUrlToUse = createSmitheryUrl(mcpServerBaseUrl, smitheryUrlOptions);
@@ -142,13 +148,74 @@ async function closeClient(client: McpClient | null) {
142148
* Main geospatial tool executor.
143149
*/
144150
export const geospatialTool = ({ uiStream }: { uiStream: ReturnType<typeof createStreamableUI> }) => ({
145-
description: `Use this tool for location-based queries including:
146-
- Finding specific places, addresses, or landmarks
147-
- Getting coordinates for locations
148-
- Distance calculations between places
149-
- Direction queries
150-
- Map-related requests
151-
- Geographic information lookup`,
151+
description: `Use this tool for location-based queries including:
152+
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
153+
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.
154+
155+
Static image tool:
156+
157+
Generates static map images using the Mapbox static image API. Features include:
158+
159+
Custom map styles (streets, outdoors, satellite, etc.)
160+
Adjustable image dimensions and zoom levels
161+
Support for multiple markers with custom colors and labels
162+
Overlay options including polylines and polygons
163+
Auto-fitting to specified coordinates
164+
165+
Category search tool:
166+
167+
Performs a category search using the Mapbox Search Box category search API. Features include:
168+
Search for points of interest by category (restaurants, hotels, gas stations, etc.)
169+
Filtering by geographic proximity
170+
Customizable result limits
171+
Rich metadata for each result
172+
Support for multiple languages
173+
174+
Reverse geocoding tool:
175+
176+
Performs reverse geocoding using the Mapbox geocoding V6 API. Features include:
177+
Convert geographic coordinates to human-readable addresses
178+
Customizable levels of detail (street, neighborhood, city, etc.)
179+
Results filtering by type (address, poi, neighborhood, etc.)
180+
Support for multiple languages
181+
Rich location context information
182+
183+
Directions tool:
184+
185+
Fetches routing directions using the Mapbox Directions API. Features include:
186+
187+
Support for different routing profiles: driving (with live traffic or typical), walking, and cycling
188+
Route from multiple waypoints (2-25 coordinate pairs)
189+
Alternative routes option
190+
Route annotations (distance, duration, speed, congestion)
191+
192+
Scheduling options:
193+
194+
Future departure time (depart_at) for driving and driving-traffic profiles
195+
Desired arrival time (arrive_by) for driving profile only
196+
Profile-specific optimizations:
197+
Driving: vehicle dimension constraints (height, width, weight)
198+
Exclusion options for routing:
199+
Common exclusions: ferry routes, cash-only tolls
200+
Driving-specific exclusions: tolls, motorways, unpaved roads, tunnels, country borders, state borders
201+
Custom point exclusions (up to 50 geographic points to avoid)
202+
GeoJSON geometry output format
203+
204+
Isochrone tool:
205+
206+
Computes areas that are reachable within a specified amount of times from a location using Mapbox Isochrone API. Features include:
207+
208+
Support for different travel profiles (driving, walking, cycling)
209+
Customizable travel times or distances
210+
Multiple contour generation (e.g., 15, 30, 45 minute ranges)
211+
Optional departure or arrival time specification
212+
Color customization for visualization
213+
214+
Search and geocode tool:
215+
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.`
216+
217+
218+
,
152219
parameters: geospatialQuerySchema,
153220
execute: async (params: z.infer<typeof geospatialQuerySchema>) => {
154221
const { queryType, includeMap = true } = params;
@@ -181,24 +248,25 @@ export const geospatialTool = ({ uiStream }: { uiStream: ReturnType<typeof creat
181248
const { tools } = await mcpClient.listTools().catch(() => ({ tools: [] }));
182249
const names = new Set(tools?.map((t: any) => t.name) || []);
183250
const prefer = (...cands: string[]) => cands.find(n => names.has(n));
251+
184252
switch (queryType) {
185-
case 'directions':
186-
case 'distance': return prefer('calculate_distance', 'mapbox_matrix', 'mapbox_directions') || 'mapbox_matrix';
187-
case 'search': return prefer('search_nearby_places', 'mapbox_geocoding') || 'mapbox_geocoding';
188-
case 'map': return prefer('generate_map_link', 'mapbox_geocoding') || 'mapbox_geocoding';
189-
case 'reverse':
190-
case 'geocode': return prefer('geocode_location', 'mapbox_geocoding') || 'mapbox_geocoding';
253+
case 'directions': return prefer('directions_tool')
254+
case 'distance': return prefer('matrix_tool');
255+
case 'search': return prefer( 'isochrone_tool','category_search_tool') || 'poi_search_tool';
256+
case 'map': return prefer('static_map_image_tool')
257+
case 'reverse': return prefer('reverse_geocode_tool');
258+
case 'geocode': return prefer('forward_geocode_tool');
191259
}
192260
})();
193261

194262
// Build arguments
195263
const toolArgs = (() => {
196264
switch (queryType) {
197-
case 'directions':
265+
case 'directions': return { waypoints: [params.origin, params.destination], includeMapPreview: includeMap, profile: params.mode };
198266
case 'distance': return { places: [params.origin, params.destination], includeMapPreview: includeMap, mode: params.mode || 'driving' };
199267
case 'reverse': return { searchText: `${params.coordinates.latitude},${params.coordinates.longitude}`, includeMapPreview: includeMap, maxResults: params.maxResults || 5 };
200268
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 }) };
201-
case 'geocode':
269+
case 'geocode':
202270
case 'map': return { searchText: params.location, includeMapPreview: includeMap, maxResults: queryType === 'geocode' ? params.maxResults || 5 : undefined };
203271
}
204272
})();
@@ -212,7 +280,7 @@ export const geospatialTool = ({ uiStream }: { uiStream: ReturnType<typeof creat
212280
while (retryCount < MAX_RETRIES) {
213281
try {
214282
toolCallResult = await Promise.race([
215-
mcpClient.callTool({ name: toolName, arguments: toolArgs }),
283+
mcpClient.callTool({ name: toolName ?? 'unknown_tool', arguments: toolArgs }),
216284
new Promise((_, reject) => setTimeout(() => reject(new Error('Tool call timeout')), 30000)),
217285
]);
218286
break;

lib/agents/writer.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,14 @@ export async function writer(
1919
uiStream.append(answerSection)
2020

2121
// Default system prompt, used if dynamicSystemPrompt is not provided
22-
const default_system_prompt = `As a professional writer, your job is to generate a comprehensive and informative, yet concise answer of 400 words or less for the given question based solely on the provided search results (URL and content). You must only use information from the provided search results. Use an unbiased and journalistic tone. Combine search results together into a coherent answer. Do not repeat text. If there are any images relevant to your answer, be sure to include them as well. Aim to directly address the user's question, augmenting your response with insights gleaned from the search results.
22+
const default_system_prompt = `As a professional writer, your job is to generate a comprehensive and informative, yet concise answer of 400 words or less for the given question based solely on the provided search results (URL and content). You must only use information from the provided search results. Use an unbiased and journalistic tone. Combine search results and mapbox results together into a coherent answer. Do not repeat text. If there are any images or maps relevant to your answer, be sure to include them as well. Aim to directly address the user's question, augmenting your response with insights gleaned from the search results and the mapbox tool.
2323
Whenever quoting or referencing information from a specific URL, always cite the source URL explicitly. Please match the language of the response to the user's language.
2424
Always answer in Markdown format. Links and images must follow the correct format.
2525
Link format: [link text](url)
2626
Image format: ![alt text](url)
27+
28+
There are also some proconfigured example queires.
29+
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'
2730
`;
2831

2932
const systemToUse = dynamicSystemPrompt && dynamicSystemPrompt.trim() !== '' ? dynamicSystemPrompt : default_system_prompt;

0 commit comments

Comments
 (0)