Skip to main content
Glama

search

Find Canadian cases, legislation, and commentary by searching with specific legal keywords. Results include ranked citations and titles. Refine by jurisdiction. Confirm sources with provided CanLII citations and URLs.

Instructions

Search CanLII for cases, legislation, and commentary by keyword. This is the primary entry point for legal research. Returns case citations and titles ranked by relevance — does NOT include keywords, dates, or URLs. Call get_case_metadata on promising results to get full details before citing a case. Search is keyword-based, not semantic — use specific legal terms rather than natural language. Common terms: 'best interests of the child', 'material change in circumstances', 'standard of review', 'duty to consult', 'reasonable expectation of privacy'. Include jurisdiction to narrow results (e.g., 'Ontario', 'Alberta'). Date filters are NOT supported on search. Always cite the CanLII citation and provide the case URL so the user can verify the source.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesFull-text search query. Can include case names, legal concepts, legislation references, or keywords.
languageNoLanguage: 'en' for English (default), 'fr' for Frenchen
resultCountNoNumber of results to return (1-100, default 10). Keep low for AI context efficiency.
offsetNoPagination offset (default 0). Use to page through results.

Implementation Reference

  • src/index.ts:116-164 (registration)
    Registration of the 'search' tool via server.tool(...) including its name, description, input schemas (Zod), and handler callback.
    // ============================================================
    // TOOL: search
    // ============================================================
    server.tool(
    	"search",
    	"Search CanLII for cases, legislation, and commentary by keyword. This is the primary entry point for legal research. " +
    	"Returns case citations and titles ranked by relevance — does NOT include keywords, dates, or URLs. " +
    	"Call get_case_metadata on promising results to get full details before citing a case. " +
    	"Search is keyword-based, not semantic — use specific legal terms rather than natural language. " +
    	"Common terms: 'best interests of the child', 'material change in circumstances', 'standard of review', " +
    	"'duty to consult', 'reasonable expectation of privacy'. Include jurisdiction to narrow results (e.g., 'Ontario', 'Alberta'). " +
    	"Date filters are NOT supported on search. Always cite the CanLII citation and provide the case URL so the user can verify the source.",
    	{
    		query: z.string()
    			.describe("Full-text search query. Can include case names, legal concepts, legislation references, or keywords."),
    		language: z.enum(["en", "fr"]).default("en")
    			.describe("Language: 'en' for English (default), 'fr' for French"),
    		resultCount: z.number().min(1).max(100).default(10)
    			.describe("Number of results to return (1-100, default 10). Keep low for AI context efficiency."),
    		offset: z.number().min(0).default(0)
    			.describe("Pagination offset (default 0). Use to page through results."),
    	},
    	async ({ query, language, resultCount, offset }) => {
    		try {
    			const params = new URLSearchParams({
    				api_key: apiKey,
    				fullText: query,
    				resultCount: resultCount.toString(),
    				offset: offset.toString(),
    			});
    
    			const response = await apiFetch(
    				`https://api.canlii.org/v1/search/${language}/?${params.toString()}`
    			);
    
    			if (!response.ok) {
    				return errorResponse(`Error: Search failed (${response.status}). The search endpoint may not be available for your API key.`);
    			}
    
    			const data = await response.json();
    			const parsed = SearchResponseSchema.parse(data);
    			return jsonResponse(parsed);
    		} catch (error) {
    			return errorResponse(
    				`Error: ${error instanceof Error ? error.message : "Unknown error"}`
    			);
    		}
    	}
    );
  • The handler function for the 'search' tool. Receives query, language, resultCount, offset; builds URLSearchParams; calls the CanLII API via apiFetch; parses response with SearchResponseSchema; returns JSON response or error.
    async ({ query, language, resultCount, offset }) => {
    	try {
    		const params = new URLSearchParams({
    			api_key: apiKey,
    			fullText: query,
    			resultCount: resultCount.toString(),
    			offset: offset.toString(),
    		});
    
    		const response = await apiFetch(
    			`https://api.canlii.org/v1/search/${language}/?${params.toString()}`
    		);
    
    		if (!response.ok) {
    			return errorResponse(`Error: Search failed (${response.status}). The search endpoint may not be available for your API key.`);
    		}
    
    		const data = await response.json();
    		const parsed = SearchResponseSchema.parse(data);
    		return jsonResponse(parsed);
    	} catch (error) {
    		return errorResponse(
    			`Error: ${error instanceof Error ? error.message : "Unknown error"}`
    		);
    	}
    }
  • SearchResponseSchema - the Zod schema used to validate the API response for search results (resultCount + array of search results).
    export const SearchResponseSchema = z.object({
        resultCount: z.number(),
        results: z.array(SearchResultSchema),
    }).passthrough();
  • SearchResultSchema - union of SearchCaseResultSchema, SearchCommentaryResultSchema, SearchLegislationResultSchema, and SearchUnknownResultSchema for parsing heterogeneous search results.
    export const SearchResultSchema = z.union([
        SearchCaseResultSchema,
        SearchCommentaryResultSchema,
        SearchLegislationResultSchema,
        SearchUnknownResultSchema,
    ]);
  • apiFetch helper - the rate-limited fetch wrapper used by the search handler to make API calls (2 req/sec, 1 concurrent, 5000/day limit).
    async function apiFetch(url: string): Promise<Response> {
    	return new Promise((resolve, reject) => {
    		requestQueue = requestQueue.then(async () => {
    			const today = new Date().toDateString();
    			if (today !== dailyResetDate) {
    				dailyCount = 0;
    				dailyResetDate = today;
    			}
    			if (dailyCount >= 5000) {
    				throw new Error("Daily API limit reached (5,000 queries). Try again tomorrow.");
    			}
    			const now = Date.now();
    			const elapsed = now - lastRequestTime;
    			if (elapsed < MIN_INTERVAL_MS) {
    				await new Promise(r => setTimeout(r, MIN_INTERVAL_MS - elapsed));
    			}
    			lastRequestTime = Date.now();
    			dailyCount++;
    			return fetch(url);
    		}).then(resolve, reject);
    	});
    }
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Description fully compensates for missing annotations by disclosing return content (citations and titles only, not keywords/dates/URLs), search nature (keyword-based), limitations (no date filters), and recommended follow-up. No contradictions.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Description is a single paragraph that covers all needed information without wasted words. Could be more structured with bullets, but each sentence adds value and it remains readable.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no output schema and no annotations, the description provides sufficient context: input, behavior, limitations, and workflow. It covers what the tool returns and what it does not, and directs the agent to next steps. Could mention error handling or permissions, but is complete for a search tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so baseline is 3. Description adds value by noting 'keep low for AI context efficiency' for resultCount, and explaining that query should include jurisdiction to narrow. These go beyond schema field descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states the tool searches CanLII for cases, legislation, and commentary by keyword, and positions it as the primary entry point for legal research. However, it does not explicitly differentiate from sibling tools like browse_legislation or get_case_metadata, though it implies they are for follow-up after search.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides explicit when-to-use guidance: 'primary entry point' and after search, 'call get_case_metadata on promising results'. Also explains search is keyword-based, not semantic, and advises including jurisdiction. Does not explicitly list situations where other tools are better, but the workflow is clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/mohammadfarooqi/canlii-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server