> ## Documentation Index
> Fetch the complete documentation index at: https://phidatainc.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Update From Lifespan

> Register a second agent and resync AgentOS from a FastAPI lifespan function.

```python update_from_lifespan.py theme={null}
"""
Update From Lifespan
====================

Demonstrates update from lifespan.
"""

from contextlib import asynccontextmanager

from agno.agent.agent import Agent
from agno.db.postgres.postgres import PostgresDb
from agno.os import AgentOS
from agno.tools.mcp import MCPTools

# ---------------------------------------------------------------------------
# Create Example
# ---------------------------------------------------------------------------

db = PostgresDb(id="basic-db", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai")

# First agent. We will add this to the AgentOS on initialization.
agent1 = Agent(
    name="First Agent",
    markdown=True,
)

# Second agent. We will add this to the AgentOS in the lifespan function.
agent2 = Agent(
    id="second-agent",
    name="Second Agent",
    tools=[MCPTools(transport="streamable-http", url="https://docs.agno.com/mcp")],
    markdown=True,
    db=db,
)


# Lifespan function receiving the AgentOS instance as parameter.
@asynccontextmanager
async def lifespan(app, agent_os):
    # Add the new Agent
    agent_os.agents.append(agent2)

    # Resync the AgentOS
    agent_os.resync(app=app)

    yield


# Setup our AgentOS with the lifespan function and the first agent.
agent_os = AgentOS(
    lifespan=lifespan,
    agents=[agent1],
    mcp_server=True,
)

# Get our app.
app = agent_os.get_app()

# Serve the app.
# ---------------------------------------------------------------------------
# Run Example
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    agent_os.serve(app="update_from_lifespan:app", reload=True)
```

## Run the Example

<Steps>
  <Snippet file="create-venv-step.mdx" />

  <Step title="Install dependencies">
    ```bash theme={null}
    uv pip install -U "agno[mcp,os]" "psycopg[binary]" openai
    ```
  </Step>

  <Step title="Export your OpenAI API key">
    <CodeGroup>
      ```bash Mac/Linux theme={null}
      export OPENAI_API_KEY="your_openai_api_key_here"
      ```

      ```bash Windows theme={null}
      $Env:OPENAI_API_KEY="your_openai_api_key_here"
      ```
    </CodeGroup>
  </Step>

  <Snippet file="run-pgvector-step.mdx" />

  <Step title="Run the example">
    Save the code above as `update_from_lifespan.py`, then run:

    ```bash theme={null}
    python update_from_lifespan.py
    ```
  </Step>
</Steps>

Full source: [cookbook/05\_agent\_os/customize/update\_from\_lifespan.py](https://github.com/agno-agi/agno/blob/main/cookbook/05_agent_os/customize/update_from_lifespan.py)
