Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions LLM_GUIDANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:**
Expand Down Expand Up @@ -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) |

Expand Down Expand Up @@ -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:**
Expand Down Expand Up @@ -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}`"

---
Expand Down Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down
18 changes: 18 additions & 0 deletions TECHNICAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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
Expand Down
103 changes: 103 additions & 0 deletions src/circuitPaths.ts
Original file line number Diff line number Diff line change
@@ -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 };
}
Loading
Loading