# npcpy

> MCP Server

Here are a few options, prioritizing clarity and SEO:

*   **AI Dev Toolkit: MCP for building & managing AI models. #AI #ML** (63 chars)
*   **npcpy: Model Context Protocol toolkit for AI development.

## Overview

- **Category:** AI
- **Language:** Python
- **Stars:** 1498
- **Forks:** 43
- **Owner:** NPC-Worldwide
- **GitHub:** https://github.com/NPC-Worldwide/npcpy
- **Created:** 2024-09-27T07:18:20+00:00
- **Updated:** 2025-07-07T10:35:22+00:00
- **Source:** https://model-context-protocol.com/servers/npcpy

## Setup

## Setup

`npcpy` is available on PyPI and can be installed using pip.

### Prerequisites

Before installing, ensure you have the necessary dependencies installed on your system.

#### Linux

```bash
# (Optional) For audio support (TTS/STT):
sudo apt-get update
sudo apt-get install -y espeak portaudio19-dev python3-pyaudio alsa-base alsa-utils libcairo2-dev libgirepository1.0-dev ffmpeg

# (Optional) For file system triggers:
sudo apt-get install -y inotify-tools

# (Optional) If you don't have Ollama installed:
curl -fsSL https://ollama.com/install.sh | sh
```

#### Mac

```bash
# (Optional) For audio support:
brew install portaudio ffmpeg pygobject3

# (Optional) For file system triggers:
brew install inotify-tools

# (Optional) If you don't have Ollama installed:
brew install ollama
brew services start ollama
```

#### Windows

1.  Download and install the Ollama executable from the [Ollama website](https://ollama.com/).
2.  Using PowerShell, install FFmpeg:

    ```powershell
    # Instructions for installing ffmpeg with chocolatey
    # choco install ffmpeg
    ```

### Installation Steps

1.  Install `npcpy` using pip:

    ```bash
    pip install npcpy
    ```

2.  (Optional) Install with extra dependencies:

    *   With API libraries:

        ```bash
        pip install 'npcpy[lite]'
        ```

    *   With full local package set up (Ollama, Diffusers, Transformers, CUDA, etc.):

        ```bash
        pip install 'npcpy[local]'
        ```

    *   For TTS/STT support:

        ```bash
        pip install 'npcpy[yap]'
        ```

    *   To install everything:

        ```bash
        pip install 'npcpy[all]'
        ```

3.  (Optional) Pull necessary models if using Ollama:

    ```bash
    ollama pull llama3.2
    ollama pull llava:7b
    ollama pull nomic-embed-text
    ```

### Configuration

1.  Run `npcsh` for the first time to generate the `.npcshrc` file:

    ```bash
    npcsh
    ```

2.  The `.npcshrc` file will be created in your home directory (`~/.npcshrc`). This file stores your `npcsh` settings. Example:

    ```bash
    # NPCSH Configuration File
    export NPCSH_INITIALIZED=1
    export NPCSH_CHAT_PROVIDER='ollama'
    export NPCSH_CHAT_MODEL='llama3.2'
    export NPCSH_DB_PATH='~/npcsh_history.db'
    ```

3.  (Optional) Add the following lines to your `.bashrc` or `.zshrc` file to source the `npcsh` configuration:

    ```bash
    # Source NPCSH configuration
    if [ -f ~/.npcshrc ]; then
        . ~/.npcshrc
    fi
    ```

### Environment Variables

To use tools that require API keys, create an `.env` file in the folder where you are working or place relevant API keys as env variables in your `~/.npcshrc`. If you already have these API keys set in a `~/.bashrc` or a `~/.zshrc` or similar files, you need not additionally add them to `~/.npcshrc` or to an `.env` file. Example `.env` file:

```bash
export OPENAI_API_KEY="your_openai_key"
export ANTHROPIC_API_KEY="your_anthropic_key"
export DEEPSEEK_API_KEY='your_deepseek_key'
export GEMINI_API_KEY='your_gemini_key'
export PERPLEXITY_API_KEY='your_perplexity_key'
```

Individual NPCs can also be set to use different models and providers by setting the `model` and `provider` keys in the NPC files.

### Project Structure

After initialization, the following directory structure will be created:

```
~/.npcsh/
├── npc_team/           # Global NPCs
│   ├── jinxs/          # Global tools
│   └── assembly_lines/ # Workflow pipelines
```

For project-specific configurations, create an `npc_team` directory in your project:

```
./npc_team/            # Project-specific NPCs
├── jinxs/             # Project jinxs
│   └── example.jinx
└── assembly_lines/    # Project workflows
    └── example.pipe
└── models/    # Project workflows
    └── example.model
└── example1.npc        # Example NPC
└── example2.npc        # Example NPC
└── team.ctx            # Example ctx
```

## Tools

## Available Tools

- **NPC (from `npcpy.npc_compiler`)**: Creates and manages AI agents with specific names, directives, models, and providers.
    ```python
    from npcpy.npc_compiler import NPC
    simon = NPC(
              name='Simon Bolivar',
              primary_directive='Liberate South America from the Spanish Royalists.',
              model='gemma3',
              provider='ollama'
              )
    response = simon.get_llm_response("What is the most important territory to retain in the Andes mountains?")
    print(response['response'])
    ```

- **Team (from `npcpy.npc_compiler`)**: Sets up and orchestrates a team of NPCs, including a forenpc to manage the team's actions.
    ```python
    from npcpy.npc_compiler import NPC, Team
    ggm = NPC(
              name='gabriel garcia marquez',
              primary_directive='You are the author gabriel garcia marquez. see the stars ',
              model='deepseek-chat',
              provider='deepseek',
              )

    isabel = NPC(
              name='isabel allende',
              primary_directive='You are the author isabel allende. visit the moon',
              model='deepseek-chat',
              provider='deepseek',
              )
    borges = NPC(
              name='jorge luis borges',
              primary_directive='You are the author jorge luis borges. listen to the earth and work with your team',
              model='gpt-4o-mini',
              provider='openai',
              )          

    # set up an NPC team with a forenpc that orchestrates the other npcs
    lit_team = Team(npcs = [ggm, isabel], forenpc=borges)

    print(lit_team.orchestrate('whats isabel working on? '))
    ```

- **get_llm_response (from `npcpy.llm_funcs`)**: Retrieves responses from LLMs, allowing for specification of model, provider, and formatting options. Can be used with or without an NPC agent.
    ```python
    from npcpy.llm_funcs import get_llm_response
    response = get_llm_response("Who was the celtic Messenger god?", model='llama3.2', provider='ollama')
    print(response['response'])
    ```
    - Supports structured outputs via `format='json'` or Pydantic schemas.
    ```python
    from npcpy.llm_funcs import get_llm_response
    response = get_llm_response("What is the sentiment of the american people towards the repeal of Roe v Wade? Return a json object with `sentiment` as the key and a float value from -1 to 1 as the value", model='gemma3:1b', provider='ollama', format='json')

    print(response['response'])
    ```
    - Supports streaming responses.
    ```python
    from npcpy.npc_sysenv import print_and_process_stream
    from npcpy.llm_funcs import get_llm_response
    response = get_llm_response("When did the united states government begin sendinng advisors to vietnam?", model='llama3.2', provider='ollama', stream = True)

    full_response = print_and_process_stream(response['response'], 'llama3.2', 'ollama')
    ```
    - Supports passing lists of messages for conversational context.
    - Supports passing attachments (images) to the LLM.
    ```python
    from npcpy.llm_funcs import get_llm_response
    messages = [{'role': 'system', 'content': 'You are an annoyed assistant.'}]

    response = get_llm_response("What is the meaning of caesar salad", model='gpt-4o-mini', provider='openai', images=['./Language_Evolution_and_Innovation_experiment.png'], messages=messages)
    ```

- **print_and_process_stream (from `npcpy.npc_sysenv`)**: Processes and prints streaming responses from LLMs.

- **gen_image (from `npcpy.llm_funcs`)**: Generates images using models from Hugging Face's diffusers library, OpenAI, or Gemini.
    ```python
    from npcpy.llm_funcs import gen_image
    image = gen_image("make a picture of the moon in the summer of marco polo", model='runwayml/stable-diffusion-v1-5', provider='diffusers')

    image = gen_image("make a picture of the moon in the summer of marco polo", model='dall-e-2', provider='openai')

    # edit images with 'gpt-image-1' or gemini's multimodal models, passing image paths, byte code images, or PIL instances.

    image = gen_image("make a picture of the moon in the summer of marco polo", model='gpt-image-1', provider='openai', attachments=['/path/to/your/image.jpg', your_byte_code_image_here, your_PIL_image_here])


    image = gen_image("edit this picture of the moon in the summer of marco polo so that it looks like it is in the winter of nishitani", model='gemini-2.0-flash', provider='gemini', attachments= [])
    ```

- **gen_video (from `npcpy.llm_funcs`)**: Generates videos using specified models and providers.
    ```python
    from npcpy.llm_funcs import gen_video
    video = gen_video("make a video of the moon in the summer of marco polo", model='runwayml/stable-diffusion-v1-5', provider='diffusers')
    ```

- **NPC Shell (`npcsh`)**: A bash-replacement shell that can process bash, natural language, or special macro calls.
    - `/search`: Web searching. Example: `/search -p perplexity 'cal bears football schedule'`
    - `/sample`: One-shot sampling. Example: `/sample 'prompt'`
    - `/vixynt`: Image generation. Example: `/vixynt 'an image of a dog eating a hat'`
    - Process Identification: `please identify the process consuming the most memory on my computer`
    - `/ots`: Screenshot analysis.
    - `/yap`: Voice chat.
    - `/plonk`: Computer use. Example: `/plonk -n 'npc_name' -sp 'task for plonk to carry out'`
    - `/spool`: Enter chat loop with an NPC. Example: `/spool -n <npc_name>`

- **`guac`**: A replacement shell for interpreters like python/r/node/julia with an avocado input marker 🥑 that brings a pomodoro-like approach to interactive coding.
    - Simulation: `🥑 Make a markov chain simulation of a random walk in 2D space with 1000 steps and visualize`
    - Access variables: `🥑 print(positions)`
    - Run a python script: `🥑 run file.py`
    - Refresh: `🥑 /refresh`
    - Show current variables: `🥑 /show`

- **`npc` CLI**: A command-line interface offering the capabilities of the npc shell from a regular bash shell.
  - **Ask a Generic Question**
    ```bash
    npc 'has there ever been a better pasta shape than bucatini?'
    ```
  - **Compile an NPC**
    ```bash
    npc compile /path/to/npc.npc
    ```
  - **Computer Use**
    ```bash
    npc plonk -n 'npc_name' -sp 'task for plonk to carry out'
    ```
  - **Generate Image**
    ```bash
    npc vixynt 'generate an image of a rabbit eating ham in the brink of dawn' model='gpt-image-1' provider='openai'
    ```
  - **Search the Web**
    ```bash
    npc search -q "cal golden bears football schedule" -sp perplexity
    ```
  - **Serve an NPC Team**
    ```bash
    npc serve --port 5337 --cors='http://localhost:5137/'
    ```
  - **Screenshot Analysis**
    ```bash
    npc ots
    ```

- **`alicanto`**: A research exploration agent flow.
    - Example: `npc alicanto "What are the implications of quantum computing for cybersecurity?"`
    - With more researchers and deeper exploration: `npc alicanto "How might climate change impact global food security?" --num-npcs 8 --depth 5`
    - Control exploration vs. exploitation balance: `npc alicanto "What ethical considerations should guide AI development?" --exploration 0.5`
    - Different output formats: `npc alicanto "What is the future of remote work?" --format report`

- **`pti`**: A reasoning REPL loop with explicit checks to request inputs from users following thinking traces.
    - Usage: `pti`

- **`spool`**: A simple agentic
