Skip to main content
Glama

UNC LibCal MCP

MCP-сервер для бронирования учебных помещений UNC Davis Library из Claude, Cursor, Codex или любого MCP-клиента — с опциональной интеграцией с Apple Calendar.

Создан для студентов, преподавателей и сотрудников UNC с действующим Onyen. Не аффилирован с UNC Libraries и не одобрен ими.

Что он делает

Спросите своего агента:

Забронируй мне куб в Davis на завтра в 14:00

Сервер:

  1. Проверит доступность в LibCal (публичный API — вход не нужен)

  2. Предложит ранжированные варианты (libcal_suggest) или забронирует слот после вашего подтверждения (libcal_book)

  3. Завершит бронирование в вашем браузерном сеансе (Playwright + сохранённый вход Onyen)

  4. При необходимости добавит событие в Apple Calendar (только macOS)

Related MCP server: @aiwerk/mcp-server-cal

Требования

  • Node.js 20+

  • UNC Onyen (для бронирования; проверка доступности работает без входа)

  • macOS для синхронизации с Apple Calendar (необязательно)

  • Chromium (устанавливается автоматически через Playwright)

Быстрый старт

1. Клонируйте и установите

git clone https://github.com/Thespaceblade/unc-libcal-mcp.git
cd unc-libcal-mcp
npm install
npx playwright install chromium
npm run build
npm test

2. Войдите в LibCal

npm run login

Откроется браузер → войдите с помощью Onyen (+ Duo, если будет предложено) → когда страница Davis LibCal загрузится, нажмите Enter в терминале.

Ваш сеанс сохраняется в ~/.unc-libcal/storage-state.json (никогда не коммитьте этот файл).

3. Настройка (необязательно)

При первом запуске создаётся ~/.unc-libcal/config.json со значениями по умолчанию:

{
  "defaultCategory": "davis-cubes",
  "calendarName": "Calendar",
  "preferSameDay": true,
  "minLeadMinutes": 30,
  "searchHorizonDays": 7,
  "bookingPurpose": "Study session"
}

Попросите агента выполнить libcal_list_calendars, затем установите calendarName на нужный календарь Apple Calendar. Предоставьте разрешение Automation, когда macOS запросит его (Terminal или Cursor → Calendar).

4. Подключите ваш MCP-клиент

Каждому клиенту нужен абсолютный путь к dist/index.js. Изнутри репозитория:

pwd   # e.g. /Users/you/projects/unc-libcal-mcp
# Use: <that-path>/dist/index.js

Или одной строкой:

node -e "const p=require('path'); console.log(p.join(process.cwd(),'dist/index.js'))"

Все клиенты ниже используют один и тот же stdio-сервер:

{
  "command": "node",
  "args": ["/absolute/path/to/unc-libcal-mcp/dist/index.js"]
}

Перезапустите клиент после изменения конфигурации.

Claude Desktop

Файл: ~/Library/Application Support/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "unc-libcal": {
      "command": "node",
      "args": ["/absolute/path/to/unc-libcal-mcp/dist/index.js"]
    }
  }
}

Полностью завершите работу Claude Desktop и откройте его заново.

Cursor

Вариант A — интерфейс: Настройки → MCP → Добавить сервер → вставьте JSON-блок выше.

Вариант B — файл проекта: .cursor/mcp.json в этом репозитории (удобно для совместной работы с коллегами):

{
  "mcpServers": {
    "unc-libcal": {
      "command": "node",
      "args": ["./dist/index.js"]
    }
  }
}

Используйте ./dist/index.js только если рабочая директория MCP в Cursor — корень проекта; в противном случае используйте абсолютный путь.

OpenAI Codex (CLI)

Codex использует TOML, а не JSON. Файл: ~/.codex/config.toml (или .codex/config.toml в доверенном проекте).

[mcp_servers.unc-libcal]
command = "node"
args = ["/absolute/path/to/unc-libcal-mcp/dist/index.js"]

Или через CLI:

codex mcp add unc-libcal -- node /absolute/path/to/unc-libcal-mcp/dist/index.js
codex mcp list   # verify it appears

Если серверы не отображаются, убедитесь, что проект доверенный (codex trust в репозитории) при использовании локального для проекта .codex/config.toml.

Claude Code (CLI)

Файл: ~/.claude.json (глобально) или .mcp.json в проекте:

{
  "mcpServers": {
    "unc-libcal": {
      "command": "node",
      "args": ["/absolute/path/to/unc-libcal-mcp/dist/index.js"]
    }
  }
}

В сеансе Claude Code выполните /mcp, чтобы убедиться, что инструменты загружены.

Другие MCP-клиенты

Любой клиент, поддерживающий stdio MCP, может использовать те же command + args. Укажите ему dist/index.js после npm run build.

5. Проверьте, что всё работает

В вашем агенте попробуйте:

Check libcal auth status

Затем:

Suggest Davis cubes for 2 hours tomorrow

После подключения сервера вы должны увидеть доступные libcal_auth_status, libcal_suggest, libcal_check_availability, libcal_book и libcal_list_calendars.

MCP-инструменты

Инструмент

Требуется вход

Назначение

libcal_suggest

Нет

Ранжированные варианты бронирования; приоритет на сегодня, если не указана дата

libcal_check_availability

Нет

Открытые слоты на одну дату

libcal_book

Да

Бронирование подтверждённого слота + опциональное событие в Apple Calendar

libcal_auth_status

Да

Проверка, действителен ли сохранённый сеанс

libcal_list_calendars

Нет

Список названий календарей Apple Calendar (macOS)

Процесс бронирования

  1. Для запросов без конкретики («забронируй куб», «максимум часов») → агент сначала вызывает libcal_suggest

  2. Агент показывает пронумерованные варианты; вы выбираете один

  3. Агент вызывает libcal_book с user_confirmed: true и выбранными датой/временем

libcal_book не будет выполнен без явного подтверждения.

Категории помещений

ID

Описание

davis-cubes

Davis Collaboration Cubes (по умолчанию)

davis-study-rooms

Групповые учебные комнаты Davis

davis-computers

Компьютеры лаборатории Data Services

Примеры запросов

Book me a study room for as long as possible
→ libcal_suggest shows TODAY vs later; you pick; then libcal_book

Book me a Davis cube tomorrow 11am–1pm
→ libcal_suggest or direct libcal_book with your exact time

Any study rooms free Friday afternoon?
→ libcal_check_availability or libcal_suggest

Как это работает

  • Доступность — реверс-инженеренный grid API LibCal (/spaces/availability/grid)

  • Бронирование — Playwright управляет реальным интерфейсом LibCal: выбор слота → отправка времени → оформление на /spaces/auth → форма подтверждения

  • Календарь — AppleScript → Calendar.app (требуется разрешение Automation в macOS)

Сеансы периодически истекают. Выполните npm run login снова, когда libcal_auth_status сообщит об истечении.

CLI-скрипты

# Refresh Onyen session
npm run login

# Run unit tests (38 tests)
npm test

# Book via CLI (uses saved session)
node dist/scripts/run-task.js --date 2026-09-01 --start 14:00 --duration 120

# Check public bookings page / cancel-link availability
node dist/scripts/list-bookings.js

Отмена бронирований

UNC LibCal не предоставляет страницу отмены «мои бронирования» в веб-интерфейсе. Отмените бронирование по ссылке в письме с подтверждением от alerts@mail.libcal.com.

Лимиты LibCal (UNC Davis)

  • До 3 часов в день, сегментами по 30 минут / 1 час

  • Популярные слоты могут быть заняты между suggest и book

  • Для кубов может потребоваться «название курса или группы» в форме оформления (по умолчанию — bookingPurpose в конфиге)

Разработка

npm run build    # compile TypeScript → dist/
npm test         # unit + integration tests
npm run dev      # build and start MCP server on stdio

Предостережения

  • Личный инструмент автоматизации — используйте ответственно и соблюдайте правила библиотеки UNC

  • Протестировано только с calendar.lib.unc.edu (UNC Chapel Hill)

  • Другим учреждениям LibCal потребуются другие константы lid/gid в src/libcal/constants.ts

Лицензия

MIT — см. LICENSE.

Available Tools

5 tools
libcal_auth_statusA

Check whether your saved UNC LibCal login session is still valid. Run npm run login in the unc-libcal-mcp project if expired.

NameRequiredDescriptionDefault

No parameters

TDQS

A4.2/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are present, so the description carries the burden. It states the tool checks a saved session and provides remediation if expired, but does not disclose the return format, whether any network call is made, or what happens with no saved session. The behavior is generally self-evident for a status check, but richer context would help.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two short sentences with no filler. The core purpose is stated first, and the actionable recovery command follows immediately. Every word earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a zero-parameter, no-output-schema tool, the description is largely complete: it states what is checked and what to do if the session is expired. A minor gap is not describing what the tool returns, but the purpose sentence implies a validity result, and the recovery step covers the main downstream need.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters, so parameter semantics are trivially satisfied. The description adds no parameter details, but none are needed. Baseline 4 applies for a no-parameter tool.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description uses a specific verb ('Check whether') and a precise resource ('saved UNC LibCal login session') with an explicit outcome (valid vs expired). The name and description together clearly distinguish this auth-status tool from the sibling booking/availability tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Clearly indicates when to use the tool: to verify saved session validity. It also gives an actionable alternative by telling the user to run 'npm run login' if expired. It doesn't enumerate when not to use it, but no sibling competes with this auth check, so the guidance is sufficient.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

libcal_bookA

Book a specific UNC LibCal slot. BOOKING WORKFLOW (required):

  1. For open-ended requests ("book a room", "max hours", "soonest available") → call libcal_suggest FIRST.

  2. Present numbered options to the user. Explain the recommended option (usually same-day if available).

  3. Only call libcal_book after the user picks an option (or gives explicit date+time).

  4. Never auto-book a far-future date when sooner options exist. Requires user_confirmed=true. Categories: davis-cubes, davis-study-rooms, davis-computers

NameRequiredDescriptionDefault
dateYesBooking date YYYY-MM-DD (from user choice or libcal_suggest option)
categoryNoSpace category id (default: davis-cubes)
space_idNoLibCal item/space id (from libcal_suggest option if available)
start_timeYesStart time HH:MM (from user choice or libcal_suggest option)
user_confirmedYesMust be true — confirms the user explicitly chose this slot
add_to_calendarNoAdd to Apple Calendar after booking (default true)
duration_minutesYesBooking length in minutes

TDQS

A4.6/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the burden of behavioral disclosure. It clearly states the user_confirmed=true requirement, the category restrictions, and the anti-far-future-booking guardrail. It could additionally mention side effects like calendar creation or failure behavior, but the key behavioral constraints are well covered.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is tightly structured with a numbered workflow and no filler. Each sentence contributes necessary operational guidance, and key constraints are front-loaded before the raw category list.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers the critical workflow context: prerequisites, confirmation requirement, category options, and when invocation is appropriate. It leaves some operational details to the schema (duration bounds, optional parameters) and doesn't describe error/return behavior, but for a booking action the core invocation context is complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so the baseline is 3. The description adds value by clarifying that date and start_time come from user choice or libcal_suggest options, that user_confirmed must be true, and by listing valid categories. This goes beyond the schema's basic descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states the tool's function: 'Book a specific UNC LibCal slot.' It distinguishes itself from siblings by describing the required prerequisite workflow with libcal_suggest and by limiting scope to confirmed, specific bookings.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides explicit, step-by-step usage guidance: call libcal_suggest first for open-ended requests, present options, only call after user picks an option or gives explicit date/time, and never auto-book a far-future date when sooner options exist. This is strong, actionable routing guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

libcal_check_availabilityA

Check open slots on ONE specific date. For smart ranked search across days, use libcal_suggest instead. Categories: davis-cubes, davis-study-rooms, davis-computers

NameRequiredDescriptionDefault
dateYesDate to check, YYYY-MM-DD
categoryNoSpace category id (default: davis-cubes)
after_timeNoOnly show slots at or after this time, HH:MM (24h)
duration_minutesNoDesired booking length in minutes (default 60)

TDQS

A4.4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. The verb 'Check' implies a non-destructive read operation, and the date-specific scope is clear. However, it does not explicitly confirm that no booking is made, nor does it mention authentication requirements or output characteristics. These gaps are notable but not severe for an availability-check tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two compact sentences plus a short category list. The core purpose is front-loaded, the differentiation is in the second sentence, and there is no wasted wording.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 4 documented parameters and a clear purpose, the description is largely complete. The category list and date-scope note cover the key details. The main omission is the response shape (what an 'open slot' looks like), which matters more because there is no output schema, but the operation is simple enough that this is a minor gap.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, giving a baseline of 3. The description adds concrete valid category values ('davis-cubes, davis-study-rooms, davis-computers'), which is not in the schema's generic 'Space category id' description. This gives the agent actionable parameter knowledge beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb and resource: 'Check open slots on ONE specific date.' It also explicitly distinguishes itself from the sibling libcal_suggest, which is the cross-day ranked search, so an agent can clearly tell them apart.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives explicit when-to-use context ('on ONE specific date') and names the alternative for a different case ('For smart ranked search across days, use libcal_suggest instead'). This directly routes the agent to the correct sibling without leaving it to inference.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

libcal_list_calendarsA

List Apple Calendar calendar names (use one in ~/.unc-libcal/config.json as calendarName).

NameRequiredDescriptionDefault

No parameters

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the behavioral burden. The verb 'List' clearly indicates a read-only operation with no destructive side effects, and the config.json reference provides useful context about where the result is consumed. It does not spell out authentication requirements, but for a simple listing tool the implied read-only nature is sufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the action and resource, then appends the one essential usage hint. There is no filler or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a zero-parameter, no-output-schema tool, the description fully covers what the tool does and why the agent would call it. It tells the agent the output (calendar names) and how to use it, making it complete enough for correct invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters, so parameter semantics are largely not applicable; the baseline for zero parameters is 4. The description adds value by explaining how the output relates to config.json, which is more than the empty schema provides.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a clear, specific action ('List') and resource ('Apple Calendar calendar names'), which is immediately distinct from the sibling tools that check availability, book, authenticate, or suggest. It also tells the agent the practical outcome, selecting a name for config.json, so the purpose is unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The parenthetical 'use one in ~/.unc-libcal/config.json as calendarName' implies when the tool is needed (before configuring a calendar) and how its output should be used. However, it does not explicitly state when to use this tool instead of a sibling, nor does it provide exclusions or prerequisites.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

libcal_suggestA

Find ranked booking options with same-day priority. Use BEFORE booking when the user has not given an exact date+time. BOOKING WORKFLOW (required):

  1. For open-ended requests ("book a room", "max hours", "soonest available") → call libcal_suggest FIRST.

  2. Present numbered options to the user. Explain the recommended option (usually same-day if available).

  3. Only call libcal_book after the user picks an option (or gives explicit date+time).

  4. Never auto-book a far-future date when sooner options exist. Categories: davis-cubes, davis-study-rooms, davis-computers

NameRequiredDescriptionDefault
categoryNoSpace category id (default: davis-cubes)
max_optionsNoHow many options to return (default 5)
preferred_dateNoUser's preferred date YYYY-MM-DD (optional, boosts ranking)
prefer_same_dayNoPrioritize today if slots exist (default true)
duration_minutesNoDesired length in minutes (default 60; use 180 for max/LibCal limit)
preferred_start_timeNoUser's preferred start HH:MM (optional, boosts ranking)

TDQS

A4.5/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses ranking behavior, same-day priority, numbered option output, and the recommended-option explanation. It does not detail return format or error/no-result behavior, but for a non-destructive suggestion tool the disclosed workflow is reasonably transparent.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose and then gives a structured, actionable workflow. There is minor redundancy between the opening 'Use BEFORE booking...' and step 1, but the numbered format and categories list keep it scannable and useful.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with six optional parameters, no output schema, and no annotations, the description plus detailed input schema covers invocation behavior, defaults, categories, and the follow-up booking step. It does not cover the exact-date+time path to libcal_check_availability or what to do when no options are found, so it is not fully complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so the baseline is 3. The description adds practical meaning beyond the schema by listing exact category values (davis-cubes, davis-study-rooms, davis-computers), clarifying duration semantics with 'use 180 for max/LibCal limit', and explaining preferred_date/preferred_start_time as ranking boosts.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific action ('Find ranked booking options') on a specific resource with a clear behavioral qualifier ('same-day priority'). It also positions the tool in the booking workflow relative to libcal_book, so an agent can distinguish when this tool is intended.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It explicitly says to use this tool BEFORE booking when the user has not given an exact date+time, provides a required numbered workflow, and names the condition for calling libcal_book instead. It also instructs the agent never to auto-book far-future dates when sooner options exist.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 5 tool updatesv0.3.0
    • First observedlibcal_auth_status
    • First observedlibcal_book
    • First observedlibcal_check_availability
    • First observedlibcal_list_calendars
    • First observedlibcal_suggest

TDQS

A4.1/5.0

Scored across 5 tools

Disambiguation4/5

The core booking tools are clearly separated: check_availability is for a single date, suggest is for ranked multi-day searching, and book handles the actual reservation. Support tools like auth_status and list_calendars are distinct, though check_availability and suggest could still cause minor confusion without their descriptions.

Naming Consistency3/5

All tools share the libcal_ prefix and snake_case, but the patterns are mixed: some are verb_noun (check_availability, list_calendars), some are bare verbs (book, suggest), and one is noun_noun (auth_status). This is readable but not fully consistent.

Tool Count5/5

Five tools is a well-scoped set for a library booking server. Each tool serves a distinct role: availability checking, ranked suggestions, booking, authentication status, and calendar configuration.

Completeness2/5

The server covers finding and booking slots but lacks obvious lifecycle operations like listing existing bookings or cancelling a booking. Users or agents needing to modify or cancel a reservation would hit a dead end, which is a significant gap for a booking-focused server.

Maintenance

ActivitySlowing
ResponsivenessUnresponsive

Related MCP Connectors

Related MCP Servers