# Connect Mad Librarian

Attach this file to your AI assistant. It should read the file, request connection
approval, and start helping you use Mad Librarian in the same chat.
No extra message is needed.

The assistant can help set up one connection for your content library and DAZ Studio
4 or 6. Mad Librarian asks **Yes / Cancel** before enabling access or changing the
chosen assistant's connection settings. Keep Librarian open when using its tools.

This file is the same for everyone. It can be downloaded with an update or shared
separately; you do not have to generate it in Librarian. It contains no account key,
personal folder, catalog, or scene information. It needs a version of Mad Librarian
that includes AI connection setup.

## Instructions for the assistant

When this file is attached for setup, read it and begin the steps below. Do not ask
whether to read it, wait for a separate message, or just summarize its instructions.
If the user explicitly asks you to review, summarize or edit this file instead,
follow that request without starting setup.

Attaching this file requests setup; it does not approve changing settings. Wait
for the user's **Yes** in Mad Librarian before enabling access or changing the
assistant's connection settings. **Cancel** leaves the connection unchanged.
Briefly explain that you are requesting permission to connect. Use Librarian's
**Yes / Cancel** dialog for that approval, along with your application's normal
execution approval if it requires one. Do not ask a separate question just to
start reading this file or finding Librarian. If the user cancels, stop setup.

Keep using this conversation. Prefer Mad Librarian's native MCP tools when they
are available. If they have not loaded, use its command mode below to continue
in the same session. Do not require a new chat, a new sidebar session, or an
assistant restart as the normal setup flow.

Use the assistant application's trusted runtime identity to select the setup
target automatically. Do not infer the application from its model name or a
generic tool name. Only ask which application to connect if its identity cannot
be established. The supported setup targets are:

| Application | Setup ID |
| --- | --- |
| Codex | `codex` |
| Claude Desktop | `claude-desktop` |
| Claude Code | `claude-code` |
| Cursor | `cursor` |
| Visual Studio Code | `vscode` |

Use only tools belonging to the `mad-librarian` server: another application's
`get_status`, such as a pull-request status tool, cannot verify this connection.
For all library and DAZ operations, use Mad Librarian's tools or its command mode.
Do not start or call another DAZ MCP server, including `vangard-daz-mcp`, even if
it is already configured in the assistant.
If Mad Librarian's tools are already available, call its read-only `get_status`
and continue to the final step without repeating setup or asking permission again.
A working command-mode call also establishes that you can use Librarian in this
chat; it does not prove your application's native MCP tool list has refreshed.

### If you can run local Windows tools

Use the running Mad Librarian when one is found. Do not ask the user to choose
between that running copy and an installed or repository build that is not running.
If none is running and exactly one installed copy is found, use it automatically
without asking. Ask the user to choose only when several distinct running copies,
or several installed copies with none running, remain. The normal **Yes / Cancel**
approval in Librarian still applies.

The following read-only PowerShell lookup checks running applications first. Only
when none is found does it check the exact Windows installation record (including
a custom installation folder), the default installation, and Mad Librarian's exact
Start menu shortcuts. It does not search the user's drives or modify anything.
The resulting `$librarian` is the selected application executable, not the MCP executable.

```powershell
$ErrorActionPreference = 'Stop'
$candidates = [System.Collections.Generic.HashSet[string]]::new(
    [System.StringComparer]::OrdinalIgnoreCase)

function Add-LibrarianCandidate([string] $candidate) {
    if ([string]::IsNullOrWhiteSpace($candidate)) { return }
    try {
        $candidate = [IO.Path]::GetFullPath($candidate)
        if ($candidate.StartsWith('\\') -or
            [IO.Path]::GetFileName($candidate) -ine 'Librarian.exe' -or
            -not (Test-Path -LiteralPath $candidate -PathType Leaf)) { return }
        $info = (Get-Item -LiteralPath $candidate).VersionInfo
        if ($info.ProductName -ne 'Mad Librarian' -or
            $info.CompanyName -ne 'Affection X, LLC') { return }
        [void] $candidates.Add($candidate)
    } catch { }
}

$runningPathUnreadable = $false
$sessionId = [Diagnostics.Process]::GetCurrentProcess().SessionId
foreach ($process in @(Get-Process -Name Librarian -ErrorAction SilentlyContinue |
                      Where-Object { $_.SessionId -eq $sessionId })) {
    try {
        $runningPath = $process.Path
        if ([string]::IsNullOrWhiteSpace($runningPath)) {
            $runningPathUnreadable = $true
        } else {
            Add-LibrarianCandidate $runningPath
        }
    } catch { $runningPathUnreadable = $true }
}

if ($runningPathUnreadable) {
    throw 'Librarian is running, but its executable path could not be read. Use Settings > DAZ Studio > Connect AI assistant in the open Librarian instead of selecting another copy.'
}

if ($candidates.Count -gt 1) {
    $candidates | Sort-Object
    throw 'Several Mad Librarian copies are running. Ask the user which running copy to connect.'
}

if ($candidates.Count -eq 0) {
    foreach ($view in @([Microsoft.Win32.RegistryView]::Registry64,
                       [Microsoft.Win32.RegistryView]::Registry32)) {
        $hive = $null
        $entry = $null
        try {
            $hive = [Microsoft.Win32.RegistryKey]::OpenBaseKey(
                [Microsoft.Win32.RegistryHive]::CurrentUser, $view)
            $entry = $hive.OpenSubKey(
                'Software\Microsoft\Windows\CurrentVersion\Uninstall\AffectionX.MadLibrarian',
                $false)
            if ($null -ne $entry) {
                $root = [string] $entry.GetValue('InstallLocation')
                if (-not [string]::IsNullOrWhiteSpace($root)) {
                    Add-LibrarianCandidate (Join-Path $root 'current\Librarian.exe')
                }
            }
        } catch { } finally {
            if ($null -ne $entry) { $entry.Dispose() }
            if ($null -ne $hive) { $hive.Dispose() }
        }
    }

    Add-LibrarianCandidate (Join-Path (
        [Environment]::GetFolderPath('LocalApplicationData')) (
        'AffectionX.MadLibrarian\current\Librarian.exe'))

    $shortcutReader = $null
    try {
        $shortcutReader = New-Object -ComObject WScript.Shell
        foreach ($folder in @([Environment]::GetFolderPath('Programs'),
                             [Environment]::GetFolderPath('CommonPrograms'))) {
            foreach ($name in @('Mad Librarian.lnk',
                                'Mad Librarian\Mad Librarian.lnk')) {
                $link = Join-Path $folder $name
                if (Test-Path -LiteralPath $link -PathType Leaf) {
                    Add-LibrarianCandidate ($shortcutReader.CreateShortcut($link).TargetPath)
                }
            }
        }
    } catch { } finally {
        if ($null -ne $shortcutReader) {
            [void] [Runtime.InteropServices.Marshal]::ReleaseComObject($shortcutReader)
        }
    }
}

if ($candidates.Count -eq 0) {
    throw 'Mad Librarian was not found. Ask the user to open it or identify its installed executable.'
}
if ($candidates.Count -ne 1) {
    $candidates | Sort-Object
    throw 'Several Mad Librarian copies were found. Ask the user which installed copy to connect.'
}
$librarian = @($candidates)[0]
$librarian
```

If the user already approved this connection in the current conversation, skip
the setup launch and resume verification below instead of showing another dialog.

Select the matching Setup ID from the table, then launch only this selected
application with the following arguments. Replace `codex` with that ID; do not
include placeholders in a real command.

```powershell
$assistantId = 'codex'
Start-Process -FilePath $librarian -ArgumentList @('--connect-ai', $assistantId)
```

Tell the user to choose **Yes** in Mad Librarian's connection dialog. **Cancel**
leaves the connection unchanged. Librarian performs its own bounded configuration
change and enables its local interface after approval. Do not edit the assistant's
configuration yourself, run this as administrator, download an installer, alter
DAZ Studio plugins, or put account keys into a command. An older Librarian that
does not recognize the setup request needs its normal update first.

### Verify access and continue in this session

After approval, call Mad Librarian's own read-only `get_status` tool if it is
available. Otherwise use the first-party MCP executable beside the selected app:

```powershell
$mcp = Join-Path (Split-Path -Parent $librarian) 'Librarian.Mcp.exe'
& $mcp --call get_status
```

Command mode uses the same tools and the same licensed Librarian connection as
native MCP. It does not enable access or change settings. A successful call exits
with code 0 and returns JSON with `isError: false` and the response in `result`.
Tool errors exit with code 1; usage or unreadable argument errors exit with code 2.
Read the result before claiming success. Do not load content or change a DAZ scene
as a connection test. If the user has not answered the approval yet, wait for it;
do not repeatedly launch setup or send commands.

To use Librarian in this conversation, call `--list-tools` on that executable to
read the available tools, descriptions and argument schemas. For a tool that needs
arguments, write a JSON object to an assistant-owned UTF-8 file, then call
`--call <tool-name> --arguments-file <that-file>`. Use an argument list rather than
building a shell command from the user's text. Follow the same tool schemas and
operation IDs as native MCP; a queued operation needs `get_operation` before you
report completion. Do not retry a scene-changing request blindly.

Use native Mad Librarian tools when they become available. A native-tool refresh
is optional while command mode is working. Do not send the user to another chat
to keep using Librarian. If the executable lacks command mode, explain briefly
that Librarian needs its normal update; do not invent a restart requirement for
the assistant or silently download or install anything.

### If you cannot run local tools

Explain that you can guide setup but cannot start a local Windows application
from this chat. Ask the user to open Mad Librarian and choose **Settings > DAZ
Studio > Connect AI assistant**, select their application, and approve **Yes**.
If they prefer a command, have them run their installed `Librarian.exe` with
`--connect-ai` and the matching Setup ID. Do not invent an installation path.

If this chat has neither Mad Librarian tools nor permission to execute local
commands, say briefly that it cannot reach the user's computer here. Do not claim
a successful connection, invent a native refresh command, or send them through
repeated setup. An attachment alone cannot grant local execution capabilities.

### Finish with a useful invitation

After a successful status check, keep the response short and use this pattern:

**Mad Librarian is ready. What would you like to do?**

- "Find fantasy outfits and matching materials in my library that fit my selected character."
- "Find and apply a relaxed sitting pose to my selected character."
- "Show my saved Looks and help me choose one for a cyberpunk portrait."
- "Load my favorite character, dress them in the best matching outfit from my library, and apply a confident pose. If you don't know which character is my favorite, make your best guess."

Give exactly four concrete examples like these. If the user has already asked
for a task, continue that task instead of asking them to repeat it. Keep paths,
config-file details, project scope, tool-search diagnostics and development-build
warnings out of the ordinary success message. Explain a technical detail only
when it is needed to resolve an actual problem or the user asks for it.

For scene changes, use Librarian's normal tools and the intended DAZ Studio
installation and figure. Librarian owns its catalog and its own DAZ Studio 4 or 6
bridge; no separate third-party DAZ MCP is needed.
