diff --git a/LLM_GUIDANCE.md b/LLM_GUIDANCE.md index 8800113..c53bbc2 100644 --- a/LLM_GUIDANCE.md +++ b/LLM_GUIDANCE.md @@ -485,6 +485,7 @@ There are **six** connectivity query types. Pick the right one using the decisio - To see upstream partner classes → use `run_query` with query_type `UpstreamClassConnectivity` (fast, pre-indexed) - To see region connectivity or neurotransmitter inputs for a neuron class → use the instance batch workflow described below - To filter by **both** upstream AND downstream class at the same time, or to retrieve results that include data from multiple connectome datasets → use `query_connectivity` (slow, live query) +- To find **indirect routes** from one class to another ("how does X reach Y?", "what pathways lead from X to Y?", "is there a circuit from X to Y?") → use `find_circuit_paths` (fast, precomputed). It needs FBbt/VFB ids, so resolve names with `search_terms` first. - Call `list_connectome_datasets` first when you need the available connectome dataset labels/IDs (e.g. to populate `query_connectivity`'s dataset filters, or to tell the user which connectomes exist). **Instance batch workflow — running individual neuron queries at the class level:** @@ -519,6 +520,7 @@ The `run_query` tool accepts an array of IDs and runs the query on all of them i | `DownstreamClassConnectivity` | Neuron class FBbt ID | Downstream partner classes with % connected, avg weight (includes data from all datasets) | Fast (pre-indexed) | | `UpstreamClassConnectivity` | Neuron class FBbt ID | Upstream partner classes with % connected, avg weight (includes data from all datasets) | Fast (pre-indexed) | | `query_connectivity` | Neuron class names or FBbt IDs | Connections between two neuron classes (includes data from all datasets) | Slow (1–5 min, live) | +| `find_circuit_paths` | FBbt class IDs or VFB neuron IDs (not labels) | Ranked multi-hop pathways from one class/neuron to another, per dataset | Fast (precomputed) | | `get_predicted_neurotransmitters` | Neuron class name or FBbt ID | Predicted NT(s) per class (or per instance), with mean confidence, as GO terms; optional per-dataset split | Live (seconds) | | `get_known_neurotransmitters` | Neuron class name or FBbt ID | Curated NT(s) for the class and subclasses, as GO terms (no confidence) | Live (seconds) | @@ -594,6 +596,32 @@ Note that a class label may be several names joined with `|` — a neuron that i - Use `group_by_class=true` for faster aggregated results. - Only use `query_connectivity` when you need both ends filtered by class. +#### For `find_circuit_paths` (multi-hop pathways) + +Use it when the user asks how one cell type reaches another through intermediate neurons. For a direct connection between two classes use `query_connectivity`; for "what is downstream of X" use `DownstreamClassConnectivity`. + +1. **Get ids.** It takes FBbt class ids or VFB neuron ids only. Resolve names with `search_terms` (`filter_types: ["neuron","class"]`). A broad class (e.g. Kenyon cell) is fine: it expands to the leaf classes beneath it, listed under each dataset's `sources`/`targets`. +2. **Call it with the defaults** (`k` 5, `min_synapses` 5, `exclude_dbs` omitted = `["hb","fafb"]`). It is fast, so there is no need to confirm parameters first. +3. **If nothing is found:** check `warnings` and `found_in` (a term absent from a dataset gives no paths there), then try `min_synapses: 1`, then `exclude_dbs: []`. Tell the user what you changed. + +**Reading the result.** +- `datasets` has one block per connectome; paths are never mixed across datasets. `shared_class_paths` lists class paths found in more than one dataset; lead with these when they exist, as they are the most robust. +- `score` is the product of the steps' input proportions (`inprop_in`: the fraction of the downstream class's synaptic input coming from the upstream class). Rank and compare paths within a dataset; don't present a score as a probability or an absolute strength. A 3-step path at 0.1 per step scores 0.001. +- Each edge also gives `synapses` and `pairs` (connected neuron pairs), which are useful to quote. +- `level` is `class` when both ends are classes and `neuron` when either end is a VFB neuron id. +- `neurons_left_out`: neurons with no single leaf cell type in that dataset are not in the class graph. If a path the user expects is missing, this may be why. +- In neuron-level paths, a neuron left out of the class graph has `class: null`, `status` (`no_leaf`: typed only to general classes; `multi_leaf`: several leaf types; `only_axis`: only transmitter, lineage or similar classes; `untyped`) and `types` (`[{id, label}]`). Name it by its types rather than calling it untyped. +- `instances` (with `instance_graph: true`): the best individual-neuron chains along a class path, as VFB ids. + +**Why the numbers differ from `query_connectivity`.** `find_circuit_paths` counts each neuron once, under its most specific cell type, and keeps datasets apart. `query_connectivity` with `group_by_class` rolls each connection up to every ancestor class and pools datasets. Both are correct for their purpose; don't compare their figures directly, and say which one you used. + +**Presenting.** Start with the query (source, target, datasets searched, data release from `run`), then the top paths as class chains with their scores, e.g.: +``` +FlyWire (fw): +1. LC12 → PVLP100 → DNp01 (giant fiber) score 7.8e-4 (2614 then 29 synapses) +2. ... +``` + ### Step 3: Present Results **Always start with a query summary:** @@ -642,6 +670,7 @@ For `query_connectivity` the summary stats are already computed for you over the - "To see which brain regions this neuron connects to, I can run a region connectivity query." - "To find what connects *back* to this type, I can swap upstream/downstream." - "To aggregate by neuron class, I can re-run with group_by_class=true." +- "To see the individual neurons along a circuit path, I can re-run find_circuit_paths with instance_graph=true." - "You can view any neuron at `https://v3.virtualflybrain.org/org.geppetto.frontend/geppetto?id={ID}`" --- @@ -908,6 +937,7 @@ A term is a template brain if its `SuperTypes` array from `get_term_info` includ - Connectivity (individual neuron): Search with `filter_types: ["has_neuron_connectivity"]` → `get_term_info` → `run_query` with `NeuronNeuronConnectivityQuery` - Connectivity (neuron class): Search with `filter_types: ["neuron", "class"]` → `run_query` with `DownstreamClassConnectivity` or `UpstreamClassConnectivity` - Connectivity (class-to-class): Search with `filter_types: ["neuron", "class"]` → `query_connectivity` (both upstream and downstream types) +- Circuit paths (multi-hop): Search with `filter_types: ["neuron", "class"]` → `find_circuit_paths` (source and target ids) - Brain region structure: Search with `filter_types: ["anatomy"]` → `get_hierarchy` with `relationship: "part_of"` - Cell type hierarchy: Search with `filter_types: ["neuron", "class"]` → `get_hierarchy` with `relationship: "subclass_of"` - Datasets: Search with `filter_types: ["dataset"]` to find available datasets diff --git a/README.md b/README.md index 67b6e80..1e8e9e6 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,7 @@ The MCP server exposes the following tools (available to assistants like Claude - `resolve_combination` — Resolve an unresolved split-GAL4 combination name or synonym into its component IDs - `list_connectome_datasets` — List available connectome datasets (e.g., Hemibrain, FAFB) - `query_connectivity` — Query connectivity across connectome datasets using upstream/downstream filters, returned as a strongest-first page plus a summary computed over every connection found +- `find_circuit_paths` — Strongest multi-hop pathways from one neuron class (or neuron) to another, searched in each connectome separately from precomputed class graphs - `get_predicted_neurotransmitters` — Predicted neurotransmitter(s) for a neuron class (and its subclasses) from per-instance connectome predictions, per instance or aggregated with mean confidence, optionally split by dataset - `get_known_neurotransmitters` — Known (curated) neurotransmitter(s) for a neuron class and its subclasses, from the ontology classification (no confidence) - `get_hierarchy` — Traverse the ontology hierarchy for a VFB ID: `part_of` (region/tissue structure) and/or `subclass_of` (cell-type taxonomy), ancestors and/or descendants @@ -345,6 +346,26 @@ Query synaptic connectivity between neuron classes across all connectome dataset - `limit` (number, optional): Rows to return, strongest first (default 50; `0` for all) - `offset` (number, optional): Row to start from within the ranking (default 0) +### find_circuit_paths +Find the strongest multi-hop pathways from one neuron class (or neuron) to another, e.g. LC12 → giant fiber. It answers from class-level graphs built with each data release (VFBquery circuit mode), so it takes well under a few seconds. + +- **Scoring:** each step is weighted by its input proportion (the fraction of the downstream class's synaptic input that comes from the upstream class). A path's score is the product of its steps, and paths are ranked best first. `normalise: "output"` uses the fraction of the upstream class's output instead. +- **Classes:** each neuron counts towards its single most specific (leaf) cell type in that connectome, so broad classes don't act as shortcuts. A broad term expands to the leaf classes beneath it. Neurons with no leaf type, or more than one, are left out and counted in `neurons_left_out`. They can still appear in neuron-level paths, with `class: null` plus `status` (why) and `types` (the most specific types they have). The figures therefore differ from `query_connectivity` with `group_by_class`, which rolls connections up to every ancestor class and pools datasets. +- **Datasets:** each connectome is searched separately; `shared_class_paths` lists class paths found in more than one. +- **Levels:** class ids at both ends search the class graph; a VFB neuron id at either end searches the neuron graph. + +**Parameters:** +- `source`, `target` (string or array, required): FBbt class ids or VFB neuron ids. Labels are refused; use `search_terms` first +- `k` (number, optional): Paths per dataset (default 5, max 20) +- `min_synapses` (number, optional): Minimum synapses per step (default 5) +- `min_inprop` (number, optional): Minimum input proportion per step (0..1, default 0) +- `normalise` (string, optional): `input` (default) or `output` +- `exclude_dbs` (array, optional): Dataset symbols to exclude (default `["hb","fafb"]`; `[]` for all) +- `instance_graph` (boolean, optional): Add the best individual-neuron chains along each class path +- `instance_k` (number, optional): Neuron chains per class path (default 3, max 10) + +Set `VFBQUERY_CIRCUIT_BASE` to send these requests to another circuit server (e.g. a local one or p3) instead of `https://v3-cached.virtualflybrain.org`. + ### get_predicted_neurotransmitters Predicted neurotransmitter(s) for a neuron class — itself or any subclass — from per-instance connectome predictions (each reconstructed neuron carries a predicted transmitter with a confidence). Aggregated to flat per-class rows by default (one per cell type × neurotransmitter, with `instances`, `percent_of_class`, `mean_confidence`); `aggregate=false` gives one row per neuron. `split_by_dataset=true` adds a `dataset` column so agreement across connectomes is visible. The neurotransmitter is a GO secretion term (`nt_id`/`nt_label`) — the same id space as `get_known_neurotransmitters`. Distinct from `get_known_neurotransmitters`, which is the curated classification without confidence. diff --git a/TECHNICAL.md b/TECHNICAL.md index 5959a50..a505e42 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -180,6 +180,7 @@ The server integrates with VirtualFlyBrain APIs: - **Search API**: `https://v3-cached.virtualflybrain.org/search` - **Facet vocabulary API**: `https://v3-cached.virtualflybrain.org/facets` - **Connectivity API**: `https://v3-cached.virtualflybrain.org/query_connectivity` +- **Circuit paths API**: `https://v3-cached.virtualflybrain.org/circuit_paths` (routed to the separate `vfbquery-circuit` deployment, not cached; `VFBQUERY_CIRCUIT_BASE` overrides the host) - **Hierarchy API**: `https://v3-cached.virtualflybrain.org/get_hierarchy` - **Entity resolution APIs**: `https://v3-cached.virtualflybrain.org/resolve_entity`, `/resolve_combination` - **Connectome dataset list**: `https://v3-cached.virtualflybrain.org/list_connectome_datasets` @@ -265,6 +266,23 @@ deterministic — the same logical pair of classes comes back as `"A|B"` on one and inflates `distinct_class_pairs`. The parts are sorted before keying, which gives one stable spelling per label set. +#### find_circuit_paths +- **Input**: `source`, `target` (id or array of ids), `k`, `min_synapses`, `min_inprop`, `normalise`, `exclude_dbs`, `instance_graph`, `instance_k` +- **Output**: the `/circuit_paths` response passed through as compact JSON: `{run, built, query, excluded_dbs, found_in, datasets[{dataset, label, symbol, level, sources, targets, neurons_left_out, paths[{score, hops, nodes, edges, instances?}], note?}], shared_class_paths, seconds, warnings?}` +- **API Call**: GET `/circuit_paths`, 1-minute timeout + +Request building is in `src/circuitPaths.ts` (unit tested in `tests/circuitPaths.test.js`). +The endpoint takes ids only and reports a label as "not found in any searched dataset", +which reads like "no connection", so labels are refused before the request with a pointer +to `search_terms`. Numeric options are range-checked against the endpoint's limits. +`exclude_dbs` omitted leaves the endpoint's default (`hb`, `fafb`); `[]` sends an empty +value, which searches everything. A `503` means the service has no graphs loaded yet +(it is starting, or a release failed to load) and is reported as "temporarily +unavailable", not as an empty result. + +The output is compact rather than indented: every node carries id, label and symbol, and +with every dataset and `instance_graph` an indented response runs to hundreds of KB. + #### resolve_entity / resolve_combination - **Input**: `name` — the raw, unresolved string as the user wrote it - **Output**: VFB/FlyBase IDs and metadata from the endpoint's tiered resolution (exact name → synonym → broad pattern match), passed through unmodified diff --git a/src/circuitPaths.ts b/src/circuitPaths.ts new file mode 100644 index 0000000..04aaeec --- /dev/null +++ b/src/circuitPaths.ts @@ -0,0 +1,103 @@ +// Request building for find_circuit_paths (VFBquery /circuit_paths, VFBquery#114). +// +// Kept out of index.ts so it can be unit tested: importing index.ts starts a +// server as a module side effect. +// +// /circuit_paths takes ids only: FBbt class ids, or VFB ids for individual +// neurons. A label would be reported as "not found in any searched dataset", +// which a model is likely to read as "no connection". So labels are refused +// here, before the request, with a pointer to search_terms. + +export const CIRCUIT_ID_PATTERN = /^(?:FBbt_\d{8}|VFB_[A-Za-z0-9]+)$/; + +export const CIRCUIT_DEFAULTS = { + k: 5, + min_synapses: 5, + min_inprop: 0, + normalise: 'input', + instance_k: 3, +} as const; + +export const CIRCUIT_MAX_K = 20; +export const CIRCUIT_MAX_INSTANCE_K = 10; + +export interface CircuitPathsArgs { + source?: string | string[]; + target?: string | string[]; + k?: number; + min_synapses?: number; + min_inprop?: number; + normalise?: string; + exclude_dbs?: string[]; + instance_graph?: boolean; + instance_k?: number; +} + +export type CircuitRequest = { params: URLSearchParams } | { error: string }; + +function terms(value: string | string[] | undefined): string[] { + const raw = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : []; + return raw.map((t) => String(t).trim()).filter((t) => t.length > 0); +} + +function wholeNumber(name: string, value: unknown, min: number, max?: number): string | null { + const n = Number(value); + if (!Number.isInteger(n) || n < min || (max !== undefined && n > max)) { + return `${name} must be a whole number ${max !== undefined ? `from ${min} to ${max}` : `of at least ${min}`} (got ${JSON.stringify(value)}).`; + } + return null; +} + +export function buildCircuitParams(args: CircuitPathsArgs): CircuitRequest { + const sources = terms(args.source); + const targets = terms(args.target); + if (!sources.length || !targets.length) { + return { error: 'find_circuit_paths needs both source and target: FBbt class ids (e.g. "FBbt_00100484") or VFB neuron ids (e.g. "VFB_fw011554").' }; + } + const notIds = [...sources, ...targets].filter((t) => !CIRCUIT_ID_PATTERN.test(t)); + if (notIds.length) { + return { + error: `find_circuit_paths takes ids only, not labels: ${notIds.map((t) => JSON.stringify(t)).join(', ')}. ` + + 'Use search_terms with filter_types ["neuron","class"] to find the FBbt id of a neuron type, ' + + 'then call find_circuit_paths with that id.', + }; + } + + const params = new URLSearchParams(); + params.set('source', sources.join(',')); + params.set('target', targets.join(',')); + + const checks: Array<[keyof CircuitPathsArgs, number, number?]> = [ + ['k', 1, CIRCUIT_MAX_K], + ['min_synapses', 0], + ['instance_k', 1, CIRCUIT_MAX_INSTANCE_K], + ]; + for (const [name, min, max] of checks) { + if (args[name] === undefined || args[name] === null) continue; + const problem = wholeNumber(name, args[name], min, max); + if (problem) return { error: problem }; + params.set(name, String(Number(args[name]))); + } + if (args.min_inprop !== undefined && args.min_inprop !== null) { + const p = Number(args.min_inprop); + if (!Number.isFinite(p) || p < 0 || p > 1) { + return { error: `min_inprop must be a number from 0 to 1 (got ${JSON.stringify(args.min_inprop)}).` }; + } + params.set('min_inprop', String(p)); + } + if (args.normalise !== undefined && args.normalise !== null && args.normalise !== '') { + const n = String(args.normalise).trim().toLowerCase(); + if (n !== 'input' && n !== 'output') { + return { error: `normalise must be "input" or "output" (got ${JSON.stringify(args.normalise)}).` }; + } + params.set('normalise', n); + } + // Omitted -> the endpoint's default (hb, fafb); [] -> every dataset. + if (Array.isArray(args.exclude_dbs)) { + params.set('exclude_dbs', args.exclude_dbs.map((s) => String(s).trim()).filter(Boolean).join(',')); + } + if (args.instance_graph !== undefined && args.instance_graph !== null) { + params.set('instance_graph', args.instance_graph ? 'true' : 'false'); + } + return { params }; +} diff --git a/src/index.ts b/src/index.ts index e4d7854..fb5fa65 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,6 +13,7 @@ import express from 'express'; import { createHash, randomUUID } from 'node:crypto'; import { shapeRunQueryResult, runQueryFailed } from './runQueryShape.js'; import { shapeCombineResult, shapeXrefResult } from './combineShape.js'; +import { buildCircuitParams, CircuitPathsArgs, CIRCUIT_MAX_K, CIRCUIT_MAX_INSTANCE_K } from './circuitPaths.js'; // Version is single-sourced from package.json so a release tag (forced into // package.json by CI before the build) flows straight into serverInfo. @@ -415,6 +416,60 @@ function setupToolHandlers(server: Server, sessionIdHolder?: RequestContext) { }, }, }, + { + name: 'find_circuit_paths', + description: 'Find the strongest multi-hop synaptic pathways from one Drosophila neuron class (or neuron) to another, e.g. "how does LC12 reach the giant fiber?" or "what routes lead from DA1 ORNs to MBON01?". Answers from precomputed graphs, so it is fast (well under a few seconds). Use this for indirect routes; for direct connections between two classes use query_connectivity, and for one-sided partner lists use run_query with UpstreamClassConnectivity / DownstreamClassConnectivity. INPUT: ids only — FBbt class ids, or VFB ids for individual neurons; labels are refused, so resolve names with search_terms (filter_types ["neuron","class"]) first. Several ids per end are allowed. SCORING: each step is weighted by its input proportion (inprop_in: the fraction of the downstream class\'s total synaptic input that comes from the upstream class); a path\'s score is the product of its steps, so a 3-step path at 0.1 per step scores 0.001. Paths are ranked best first; scores are comparable within a dataset, not as absolute strengths. normalise="output" uses the fraction of the upstream class\'s output instead. HOW CLASSES ARE COUNTED: each neuron is assigned to its single most specific (leaf) cell type in that connectome, so broad classes do not act as shortcuts. A broad term such as "Kenyon cell" expands to the leaf classes beneath it (listed under sources/targets). Neurons with no leaf type, or more than one, are left out (neurons_left_out counts them). They can still appear in neuron-level paths, as nodes with class null plus status (no_leaf: only general types; multi_leaf: several leaf types; only_axis: only transmitter/lineage-type classes; untyped) and types (the most specific types they do have). Because of this the figures differ from query_connectivity with group_by_class=true, which rolls connections up to every ancestor class and pools datasets: do not compare the two numbers directly. LEVELS: if both ends are classes the search runs on the class graph; if either end is a VFB neuron id, it runs on the neuron graph (class ends expand to their neurons). DATASETS: each connectome is searched separately and reported in its own block; shared_class_paths lists class paths found in more than one dataset, which are the most robust. instance_graph=true adds the best individual-neuron chains along each class path. RECOMMENDED DEFAULTS: k=5, min_synapses=5, exclude_dbs omitted (= ["hb","fafb"]). If no paths are found, try min_synapses=1, then exclude_dbs=[]. Every response names the data release (run) it came from.', + inputSchema: { + type: 'object', + properties: { + source: { + oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }], + description: 'Start of the path: FBbt class id(s) (e.g. "FBbt_00100484") or VFB neuron id(s) (e.g. "VFB_fw011554"). A broad class expands to its leaf classes. Not labels — use search_terms first.', + }, + target: { + oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }], + description: 'End of the path, in the same form as source.', + }, + k: { + type: 'number', + description: `Paths to return per dataset, best first (default 5, max ${CIRCUIT_MAX_K}).`, + default: 5, + }, + min_synapses: { + type: 'number', + description: 'Ignore class-to-class (or neuron-to-neuron) connections with fewer synapses than this (default 5). Lower to 1 if nothing is found.', + default: 5, + }, + min_inprop: { + type: 'number', + description: 'Ignore steps whose input proportion is below this (0..1, default 0). Raise it (e.g. 0.01) to keep only substantial steps.', + default: 0, + }, + normalise: { + type: 'string', + enum: ['input', 'output'], + description: '"input" (default): weight each step by the fraction of the downstream partner\'s input. "output": by the fraction of the upstream partner\'s output.', + default: 'input', + }, + exclude_dbs: { + type: 'array', + items: { type: 'string' }, + description: 'Dataset symbols to leave out. Omit for the default (["hb","fafb"], as on query_connectivity); pass [] to search every dataset. Must be symbols from list_connectome_datasets — an unknown name is rejected.', + }, + instance_graph: { + type: 'boolean', + description: 'If true, add the best individual-neuron chains along each class path (instances). Slower (about a second). Default false.', + default: false, + }, + instance_k: { + type: 'number', + description: `Neuron chains per class path when instance_graph is true (default 3, max ${CIRCUIT_MAX_INSTANCE_K}).`, + default: 3, + }, + }, + required: ['source', 'target'], + }, + }, { name: 'get_predicted_neurotransmitters', description: 'Get the PREDICTED neurotransmitter(s) for a Drosophila neuron class — itself or any subclass — from per-instance connectome predictions (each reconstructed neuron carries a predicted transmitter with a confidence). Use this for "what neurotransmitter does use?" when you want the data-driven prediction and its confidence. By default results are aggregated to flat per-class rows (one per cell type × neurotransmitter) with instance counts, percent_of_class and mean_confidence; set aggregate=false for one row per individual neuron. Set split_by_dataset=true to get one row per (cell type, neurotransmitter, dataset) so you can see agreement across connectomes. The neurotransmitter is reported as a GO secretion term (nt_id/nt_label), the same id space as get_known_neurotransmitters. This is distinct from get_known_neurotransmitters, which returns the ontology-curated classification without confidence. CONSTRAINTS: neuron class terms only (FBbt id or label); use search_terms with filter_types ["neuron","class"] to canonicalize. RECOMMENDED: exclude_dbs defaults to ["hb","fafb"]; pass [] for all datasets.', @@ -591,6 +646,8 @@ function setupToolHandlers(server: Server, sessionIdHolder?: RequestContext) { return await handleListConnectomeDatasets(); case 'query_connectivity': return await handleQueryConnectivity(args as { upstream_type?: string; downstream_type?: string; weight?: number; group_by_class?: boolean; exclude_dbs?: string[]; limit?: number; offset?: number }); + case 'find_circuit_paths': + return await handleFindCircuitPaths(args as CircuitPathsArgs); case 'get_predicted_neurotransmitters': return await handleGetPredictedNeurotransmitters(args as { neuron_type: string; aggregate?: boolean; split_by_dataset?: boolean; exclude_dbs?: string[]; min_confidence?: number }); case 'get_known_neurotransmitters': @@ -1430,6 +1487,35 @@ async function handleQueryConnectivity(args: { } } +// Circuit paths come from a separate small service (VFBquery circuit mode), +// routed at /circuit_paths on the same host. VFBQUERY_CIRCUIT_BASE points the +// tool elsewhere, e.g. a local or p3 circuit server for testing. +const CIRCUIT_BASE = process.env.VFBQUERY_CIRCUIT_BASE || VFBQUERY_BASE; + +async function handleFindCircuitPaths(args: CircuitPathsArgs): Promise<{ content: Array<{ type: string; text: string }> }> { + const built = buildCircuitParams(args || {}); + if ('error' in built) { + return { content: [{ type: 'text', text: `Error: ${built.error}` }] }; + } + const url = `${CIRCUIT_BASE}/circuit_paths?${built.params.toString()}`; + console.error(`MCP Debug: find_circuit_paths params=${built.params.toString()}`); + try { + const response = await axios.get(url, { timeout: 60000 }); + // Compact: every node carries id/label/symbol, and with every dataset and + // instance_graph an indented response runs to hundreds of KB. + return { content: [{ type: 'text', text: JSON.stringify(response.data) }] }; + } catch (error: any) { + if (error?.response?.status === 503) { + return { content: [{ type: 'text', text: `Circuit paths are temporarily unavailable (the circuit graphs are not loaded yet). This is not a "no paths" result; try again in a minute. ${rejectionDetail(error) || ''}`.trim() }] }; + } + const detail = rejectionDetail(error); + if (detail) { + return { content: [{ type: 'text', text: `Circuit path request rejected: ${detail}` }] }; + } + return { content: [{ type: 'text', text: `Error finding circuit paths: ${error}` }] }; + } +} + async function handleGetPredictedNeurotransmitters(args: { neuron_type: string; aggregate?: boolean; @@ -1833,6 +1919,7 @@ function getHtmlPage(): string {
  • resolve_combination - Resolve an unresolved split-GAL4 combination name or synonym to its underlying IDs
  • list_connectome_datasets - List available connectome datasets (e.g., Hemibrain, FAFB)
  • query_connectivity - Query connectivity across connectome datasets using upstream/downstream filters, paged with summary statistics
  • +
  • find_circuit_paths - Strongest multi-hop pathways between neuron classes (or neurons), searched in each connectome separately from precomputed class graphs
  • get_hierarchy - Build a part_of or subclass_of hierarchy tree for a VFB term
  • lookup_xref - Map a VFB ID to its external database accessions, or a confirmed external accession (e.g. a hemibrain bodyId) back to the VFB term that carries it
  • combine_queries - Boolean set algebra (AND, OR, NOT, XOR…) over the results of two or more queries, with a step trace and a plain-English reading of the expression
  • diff --git a/tests/circuitPaths.test.js b/tests/circuitPaths.test.js new file mode 100644 index 0000000..559fac8 --- /dev/null +++ b/tests/circuitPaths.test.js @@ -0,0 +1,67 @@ +// Request building for find_circuit_paths (VFBquery /circuit_paths). +// +// Run: npm test (compiles first — this exercises dist/, not src/) + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); + +const { buildCircuitParams } = require('../dist/circuitPaths.js'); + +const LC12 = 'FBbt_00100484'; +const GF = 'FBbt_00004020'; + +function params(args) { + const out = buildCircuitParams(args); + assert.ok(!('error' in out), `unexpected error: ${out.error}`); + return Object.fromEntries(out.params); +} + +test('only the ends are sent when nothing else is given, so the endpoint defaults apply', () => { + assert.deepEqual(params({ source: LC12, target: GF }), { source: LC12, target: GF }); +}); + +test('several ids per end are accepted as an array or a comma-separated string', () => { + const p = params({ source: [LC12, ' FBbt_00003686 '], target: `${GF}, VFB_fw011554` }); + assert.equal(p.source, `${LC12},FBbt_00003686`); + assert.equal(p.target, `${GF},VFB_fw011554`); +}); + +test('labels are refused with a pointer to search_terms, not sent', () => { + const out = buildCircuitParams({ source: 'Kenyon cell', target: GF }); + assert.match(out.error, /ids only/); + assert.match(out.error, /"Kenyon cell"/); + assert.match(out.error, /search_terms/); +}); + +test('both ends are required', () => { + assert.match(buildCircuitParams({ source: LC12 }).error, /both source and target/); + assert.match(buildCircuitParams({ source: [], target: GF }).error, /both source and target/); +}); + +test('exclude_dbs: omitted keeps the default, [] searches every dataset', () => { + assert.equal('exclude_dbs' in params({ source: LC12, target: GF }), false); + assert.equal(params({ source: LC12, target: GF, exclude_dbs: [] }).exclude_dbs, ''); + assert.equal(params({ source: LC12, target: GF, exclude_dbs: ['hb', ' mc '] }).exclude_dbs, 'hb,mc'); +}); + +test('options are passed through in the endpoint\'s spelling', () => { + const p = params({ + source: LC12, target: GF, k: 10, min_synapses: 0, min_inprop: 0.01, + normalise: 'Output', instance_graph: true, instance_k: 2, + }); + assert.deepEqual(p, { + source: LC12, target: GF, k: '10', min_synapses: '0', min_inprop: '0.01', + normalise: 'output', instance_graph: 'true', instance_k: '2', + }); +}); + +test('out-of-range options are refused before the request', () => { + const base = { source: LC12, target: GF }; + assert.match(buildCircuitParams({ ...base, k: 0 }).error, /k must be/); + assert.match(buildCircuitParams({ ...base, k: 21 }).error, /k must be/); + assert.match(buildCircuitParams({ ...base, k: 2.5 }).error, /k must be/); + assert.match(buildCircuitParams({ ...base, min_synapses: -1 }).error, /min_synapses/); + assert.match(buildCircuitParams({ ...base, min_inprop: 2 }).error, /min_inprop/); + assert.match(buildCircuitParams({ ...base, normalise: 'both' }).error, /normalise/); + assert.match(buildCircuitParams({ ...base, instance_k: 11 }).error, /instance_k/); +});