Metadata-Version: 2.3
Name: brown-octopus
Version: 0.4.5
Summary: Capability-context management for tool-using AI agents
Keywords: AI agents,MCP,tool retrieval,capability context
Author: nana brown
Author-email: nana brown <nanabrownsnr@gmail.com>
License:                                  Apache License
                                    Version 2.0, January 2004
                                 http://www.apache.org/licenses/
         
            TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
         
            1. Definitions.
         
               "License" shall mean the terms and conditions for use, reproduction,
               and distribution as defined by Sections 1 through 9 of this document.
         
               "Licensor" shall mean the copyright owner or entity authorized by
               the copyright owner that is granting the License.
         
               "Legal Entity" shall mean the union of the acting entity and all
               other entities that control, are controlled by, or are under common
               control with that entity. For the purposes of this definition,
               "control" means (i) the power, direct or indirect, to cause the
               direction or management of such entity, whether by contract or
               otherwise, or (ii) ownership of fifty percent (50%) or more of the
               outstanding shares, or (iii) beneficial ownership of such entity.
         
               "You" (or "Your") shall mean an individual or Legal Entity
               exercising permissions granted by this License.
         
               "Source" form shall mean the preferred form for making modifications,
               including but not limited to software source code, documentation
               source, and configuration files.
         
               "Object" form shall mean any form resulting from mechanical
               transformation or translation of a Source form, including but
               not limited to compiled object code, generated documentation,
               and conversions to other media types.
         
               "Work" shall mean the work of authorship, whether in Source or
               Object form, made available under the License, as indicated by a
               copyright notice that is included in or attached to the work
               (an example is provided in the Appendix below).
         
               "Derivative Works" shall mean any work, whether in Source or Object
               form, that is based on (or derived from) the Work and for which the
               editorial revisions, annotations, elaborations, or other modifications
               represent, as a whole, an original work of authorship. For the purposes
               of this License, Derivative Works shall not include works that remain
               separable from, or merely link (or bind by name) to the interfaces of,
               the Work and Derivative Works thereof.
         
               "Contribution" shall mean any work of authorship, including
               the original version of the Work and any modifications or additions
               to that Work or Derivative Works thereof, that is intentionally
               submitted to Licensor for inclusion in the Work by the copyright owner
               or by an individual or Legal Entity authorized to submit on behalf of
               the copyright owner. For the purposes of this definition, "submitted"
               means any form of electronic, verbal, or written communication sent
               to the Licensor or its representatives, including but not limited to
               communication on electronic mailing lists, source code control systems,
               and issue tracking systems that are managed by, or on behalf of, the
               Licensor for the purpose of discussing and improving the Work, but
               excluding communication that is conspicuously marked or otherwise
               designated in writing by the copyright owner as "Not a Contribution."
         
               "Contributor" shall mean Licensor and any individual or Legal Entity
               on behalf of whom a Contribution has been received by Licensor and
               subsequently incorporated within the Work.
         
            2. Grant of Copyright License. Subject to the terms and conditions of
               this License, each Contributor hereby grants to You a perpetual,
               worldwide, non-exclusive, no-charge, royalty-free, irrevocable
               copyright license to reproduce, prepare Derivative Works of,
               publicly display, publicly perform, sublicense, and distribute the
               Work and such Derivative Works in Source or Object form.
         
            3. Grant of Patent License. Subject to the terms and conditions of
               this License, each Contributor hereby grants to You a perpetual,
               worldwide, non-exclusive, no-charge, royalty-free, irrevocable
               (except as stated in this section) patent license to make, have made,
               use, offer to sell, sell, import, and otherwise transfer the Work,
               where such license applies only to those patent claims licensable
               by such Contributor that are necessarily infringed by their
               Contribution(s) alone or by combination of their Contribution(s)
               with the Work to which such Contribution(s) was submitted. If You
               institute patent litigation against any entity (including a
               cross-claim or counterclaim in a lawsuit) alleging that the Work
               or a Contribution incorporated within the Work constitutes direct
               or contributory patent infringement, then any patent licenses
               granted to You under this License for that Work shall terminate
               as of the date such litigation is filed.
         
            4. Redistribution. You may reproduce and distribute copies of the
               Work or Derivative Works thereof in any medium, with or without
               modifications, and in Source or Object form, provided that You
               meet the following conditions:
         
               (a) You must give any other recipients of the Work or
                   Derivative Works a copy of this License; and
         
               (b) You must cause any modified files to carry prominent notices
                   stating that You changed the files; and
         
               (c) You must retain, in the Source form of any Derivative Works
                   that You distribute, all copyright, patent, trademark, and
                   attribution notices from the Source form of the Work,
                   excluding those notices that do not pertain to any part of
                   the Derivative Works; and
         
               (d) If the Work includes a "NOTICE" text file as part of its
                   distribution, then any Derivative Works that You distribute must
                   include a readable copy of the attribution notices contained
                   within such NOTICE file, excluding those notices that do not
                   pertain to any part of the Derivative Works, in at least one
                   of the following places: within a NOTICE text file distributed
                   as part of the Derivative Works; within the Source form or
                   documentation, if provided along with the Derivative Works; or,
                   within a display generated by the Derivative Works, if and
                   wherever such third-party notices normally appear. The contents
                   of the NOTICE file are for informational purposes only and
                   do not modify the License. You may add Your own attribution
                   notices within Derivative Works that You distribute, alongside
                   or as an addendum to the NOTICE text from the Work, provided
                   that such additional attribution notices cannot be construed
                   as modifying the License.
         
               You may add Your own copyright statement to Your modifications and
               may provide additional or different license terms and conditions
               for use, reproduction, or distribution of Your modifications, or
               for any such Derivative Works as a whole, provided Your use,
               reproduction, and distribution of the Work otherwise complies with
               the conditions stated in this License.
         
            5. Submission of Contributions. Unless You explicitly state otherwise,
               any Contribution intentionally submitted for inclusion in the Work
               by You to the Licensor shall be under the terms and conditions of
               this License, without any additional terms or conditions.
               Notwithstanding the above, nothing herein shall supersede or modify
               the terms of any separate license agreement you may have executed
               with Licensor regarding such Contributions.
         
            6. Trademarks. This License does not grant permission to use the trade
               names, trademarks, service marks, or product names of the Licensor,
               except as required for reasonable and customary use in describing the
               origin of the Work and reproducing the content of the NOTICE file.
         
            7. Disclaimer of Warranty. Unless required by applicable law or
               agreed to in writing, Licensor provides the Work (and each
               Contributor provides its Contributions) on an "AS IS" BASIS,
               WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
               implied, including, without limitation, any warranties or conditions
               of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
               PARTICULAR PURPOSE. You are solely responsible for determining the
               appropriateness of using or redistributing the Work and assume any
               risks associated with Your exercise of permissions under this License.
         
            8. Limitation of Liability. In no event and under no legal theory,
               whether in tort (including negligence), contract, or otherwise,
               unless required by applicable law (such as deliberate and grossly
               negligent acts) or agreed to in writing, shall any Contributor be
               liable to You for damages, including any direct, indirect, special,
               incidental, or consequential damages of any character arising as a
               result of this License or out of the use or inability to use the
               Work (including but not limited to damages for loss of goodwill,
               work stoppage, computer failure or malfunction, or any and all
               other commercial damages or losses), even if such Contributor
               has been advised of the possibility of such damages.
         
            9. Accepting Warranty or Additional Liability. While redistributing
               the Work or Derivative Works thereof, You may choose to offer,
               and charge a fee for, acceptance of support, warranty, indemnity,
               or other liability obligations and/or rights consistent with this
               License. However, in accepting such obligations, You may act only
               on Your own behalf and on Your sole responsibility, not on behalf
               of any other Contributor, and only if You agree to indemnify,
               defend, and hold each Contributor harmless for any liability
               incurred by, or claims asserted against, such Contributor by reason
               of your accepting any such warranty or additional liability.
         
            END OF TERMS AND CONDITIONS
         
            APPENDIX: How to apply the Apache License to your work.
         
               To apply the Apache License to your work, attach the following
               boilerplate notice, with the fields enclosed by brackets "[]"
               replaced with your own identifying information. (Don't include
               the brackets!)  The text should be enclosed in the appropriate
               comment syntax for the file format. We also recommend that a
               file or class name and description of purpose be included on the
               same "printed page" as the copyright notice for easier
               identification within third-party archives.
         
            Copyright [yyyy] [name of copyright owner]
         
            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
            You may obtain a copy of the License at
         
                http://www.apache.org/licenses/LICENSE-2.0
         
            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Requires-Dist: fastmcp>=4.0.3
Requires-Dist: numpy>=2.5.3
Requires-Dist: packaging>=24.0
Requires-Dist: sentence-transformers>=6.0.1
Requires-Dist: spacy>=3.8.16
Requires-Dist: jev-reranker>=0.1.0 ; extra == 'jev'
Requires-Dist: fastapi>=0.115.0 ; extra == 'service'
Requires-Dist: uvicorn[standard]>=0.34.0 ; extra == 'service'
Requires-Dist: pyarrow>=18.0.0 ; extra == 'toolret'
Requires-Python: >=3.13
Project-URL: Repository, https://github.com/nanabrownsnr/brownoctopus
Project-URL: Documentation, https://github.com/nanabrownsnr/brownoctopus/blob/main/docs/production.md
Project-URL: Issues, https://github.com/nanabrownsnr/brownoctopus/issues
Provides-Extra: jev
Provides-Extra: service
Provides-Extra: toolret
Description-Content-Type: text/markdown

# Brown Octopus

Brown Octopus is a Python library for dynamic capability-context management
for tool-using AI agents. It determines which capability definitions should be
available to an agent on each interaction. It does not execute tools, manage
credentials, or replace the host agent framework.

## Install

```bash
pip install brown-octopus
brown-octopus setup-models
```

`setup-models` explicitly prepares `en_core_web_trf` and
`Qwen/Qwen3-Embedding-0.6B` in Brown Octopus-managed persistent storage.
Normal initialization does not download models.

## Quick start

```python
from brown_octopus import Octopus


async def main():
    octopus = Octopus()
    await octopus.initialize()

    result = octopus.retrieve_result(
        "Reply to Tom's email",
        session_id="conversation-123",
    )

    # Final active capability context for the host agent.
    for capability in result.tools:
        print(capability["name"])
```

Use `await octopus.update()` when the host deliberately wants to discover
capabilities and build an updated index. `initialize()` loads existing local
models and index state; it does not discover or download implicitly.

### Build or update an index

The repository includes a runnable example for building the persisted index
from an MCP catalog:

```bash
brown-octopus setup-models
python examples/setup_index.py
```

By default it reads `data/mcps.json` and writes `data/indexes/default`. Use a
different catalog or output directory when needed:

```bash
python examples/setup_index.py \
  --catalog path/to/my-mcps.json \
  --index path/to/my-index
```

The host can perform the same operation in application code:

```python
from brown_octopus import Octopus

octopus = Octopus(
    catalog_path="path/to/my-mcps.json",
    index_path="path/to/my-index",
)
report = await octopus.update()
print(report.tool_count)
```

An update is not a blind append and it is not an unconditional reset. Brown
Octopus compares capabilities by stable `capability_id`:

```text
new capability       -> added
same ID, new metadata -> changed/replaced
same ID, unchanged    -> retained
missing from an authoritative source snapshot -> removed
temporarily failed source -> previous capabilities preserved
```

So if you add a new MCP entry to the catalog and run the update, its
capabilities are added to the existing universe. If you remove an MCP from an
authoritative catalog, its capabilities are removed. A source failure is not
treated as deletion.

For a standalone capabilities JSON file, implement a `CapabilitySource` that
reads that file and returns a `CapabilityDiscoveryResult`; `update()` uses the
source snapshot and does not automatically scan arbitrary files placed beside
the index.

## Frozen V3 pipeline

```text
user request
    -> deterministic spaCy operational-intent analysis
    -> capability-oriented retrieval text
    -> Qwen dense retrieval
    -> Min-4 + Bounded Max Gap selection
    -> merge and deduplicate
    -> session capability state
    -> final active capability context
    -> host agent
```

```text
Embedding:        Qwen/Qwen3-Embedding-0.6B
Analyzer:         en_core_web_trf
Representation:   capability name + description
MIN_TOOLS:        4 per intent
MAX_TOOLS:        16 per intent
MIN_GAP_PERCENT:  2.0
TTL:              8 turns
Active cap:       30 capabilities
```

Brown Octopus is intentionally recall-oriented for its first production
version. It prefers a bounded set of plausible capabilities over aggressively
pruning and risking a missing required capability. It does not guarantee
perfect recall.

## Results and sessions

```python
result = octopus.retrieve_result(query, session_id="conversation-123")
```

```text
result.retrieved_tools  capabilities selected on this turn
result.tools            final active context after TTL/session management
result.tool_ids         IDs in result.tools
result.session_id       session identifier
result.turn             session turn number
```

Expose `result.tools` to the agent. Brown Octopus returns definitions and
metadata only; the host binds and executes tools.

One engine can serve many isolated conversations. Models, indexes, and
retrievers are shared; turn counters, TTL state, and active capabilities are
session-specific.

```python
octopus.reset_session("conversation-123")
octopus.delete_session("conversation-123")
snapshot = octopus.get_session("conversation-123")
```

The default `InMemorySessionStore` keeps serializable capability state in
process. Applications needing persistence can inject a custom store:

```python
octopus = Octopus(session_store=my_store)
```

Custom stores must make session mutation atomic across workers/processes.
Brown Octopus stores capability state, not conversation history.

## Building and updating the capability index

Brown Octopus separates model setup, capability discovery/indexing, and normal
runtime initialization:

```text
setup-models       prepare runtime models
    -> update()    discover capabilities and build/update the index
    -> initialize() load the existing index for runtime use
```

Prepare models first:

```bash
uv add brown-octopus
uv run brown-octopus setup-models
uv run brown-octopus doctor
```

The repository includes a runnable index setup example:

```bash
python examples/setup_index.py
```

By default it reads `data/mcps.json` and writes `data/indexes/default`. Paths
can be changed explicitly:

```bash
python examples/setup_index.py \
  --catalog path/to/my-mcps.json \
  --index path/to/my-index
```

The same operation can be performed in application code:

```python
from brown_octopus import Octopus


async def build_index():
    octopus = Octopus(
        catalog_path="data/mcps.json",
        index_path="data/indexes/default",
    )
    report = await octopus.update()
    print(report.tool_count)
```

`update()` synchronizes the configured capability source. It currently
rediscovers all configured sources and rebuilds embeddings for the complete
resulting universe before atomically publishing the new snapshot. It does not
yet provide a separate additive-only or incremental-embedding operation.

Capabilities are compared by stable identity:

```text
new capability       -> added
same ID, new metadata -> changed/replaced
same ID, unchanged    -> retained
missing from an authoritative snapshot -> removed
temporarily failed source -> previous capabilities preserved
```

Therefore, to add an MCP while preserving the existing universe, add it to the
existing catalog and run `update()` again:

```text
data/mcps.json
├── existing MCP servers
└── new MCP server
```

Passing a separate file containing only the new MCP makes that file the
configured source snapshot; it does not automatically append to the previous
catalog. An arbitrary capabilities JSON file is not scanned automatically.
For that case, implement a `CapabilitySource` that reads the file and returns
a `CapabilityDiscoveryResult`.

The default source is MCP-backed, but the abstraction is provider-neutral:

```python
octopus = Octopus(capability_source=my_source)
report = await octopus.update()
```

Capability identity fields are:

```text
capability_id  stable globally unique capability identity
source_id      discovery provenance
mcp_url        execution endpoint when applicable
```

The host controls when discovery occurs. Brown Octopus does not run a
scheduler or rediscover capabilities during `initialize()`.

## Model storage and diagnostics

Override the managed model directory for containers or shared volumes with
`BROWN_OCTOPUS_MODEL_DIR`. Model setup remains explicit:

```bash
brown-octopus setup-models
brown-octopus doctor
brown-octopus inspect
brown-octopus inspect --json
```

`doctor` checks package, model, and index readiness. `inspect` reports the
active index and frozen configuration without exposing credentials.

## Architecture boundary

Brown Octopus owns intent analysis, capability retrieval/selection, index
construction, active capability context, session capability state, and
explicit capability updates.

The host owns the LLM, conversation history, tool binding/execution,
credentials, authentication, authorization, user identity, refresh timing,
and session lifecycle policy.

Brown Octopus is harness-agnostic. A LangGraph integration example is available
at [`examples/langgraph_app`](examples/langgraph_app/README.md); LangGraph is
not a runtime dependency.

## Development

```bash
uv sync
brown-octopus setup-models
uv run pytest -m "not external"
uv build
```

Historical evaluation infrastructure remains under `evals/`, benchmark data
under `data/evals/`, and research outputs under `results/`. These are separate
from the installable `brown_octopus` package.

See [`LICENSE`](LICENSE) for licensing information.
