Logo n2-qln

n2-qln

Cộng đồng
choihyunsus

n2-QLN: Intelligent Tool Router & Semantic Search Layer for MCP. Connect 1,000+ tools through 1 interface. Prevent AI model confusion and maximize context window efficiency

Nhà phát hànhchoihyunsus
Kho mãn2-QLN
Ngôn ngữTypeScript
Bản fork
7
Sao
43
Công cụ có sẵn
1
Phương thức truyền tảistdio
Danh mục
Liên kết
  • Kết nối công cụ với quy trình làm việc AI

    n2-qln cung cấp các chức năng MCP cho các ứng dụng khách AI và tác nhân AI tương thích.

  • 1 công cụ có sẵn

    Xem các thao tác có thể gọi bên dưới, kèm tên và mô tả nếu máy chủ cung cấp.

  • Mẫu cấu hình có thể sao chép ngay

    Dùng các đoạn cấu hình mẫu để thiết lập máy chủ này trong ứng dụng khách MCP bạn muốn dùng.

  • Mức độ quan tâm của cộng đồng đến kho mã

    43 sao và 7 bản fork từ kho mã được liên kết.

🇰🇷 한국어

n2-qln

npm license node downloads

QLN = Query Layer Network — a semantic tool router that sits between the AI and your tools.

Route 1,000+ tools through 1 MCP tool. The AI sees only the router — not all 1,000 tools.

QLN Architecture — Without vs With

Table of Contents

Why QLN

Every MCP tool eats context tokens. 10 tools? Fine. 100? Slow. 1,000? Impossible — context is full before the conversation starts.

QLN solves this:

  1. All tools are indexed in QLN's SQLite engine
  2. The AI sees one tool: n2_qln_call (~200 tokens)
  3. AI searches → finds the best match → executes with automatic fallback

Result: ~200 tokens instead of ~50,000. 99.6% reduction.

Features

FeatureDescription
1 tool = 1,000 toolsAI sees n2_qln_call (~200 tokens), QLN routes to the right one
Sub-5ms search3-stage engine: trigger match → BM25 keyword → semantic vector
Auto modeOne-shot search + execute with confidence gating and fallback chain
Circuit BreakerAuto-disable failing tools, self-recover after timeout
MCP Auto-DiscoveryScan external MCP servers and index their tools automatically
Boost KeywordsCurated terms with 2× BM25 weight for precision search
Self-learning rankingUsage count + success rate feed back into scores
Source weightingPrioritize tools by origin (mcp > plugin > local)
Hot reloadEdit providers/ manifests at runtime — auto re-indexed
Bulk injectRegister hundreds of tools in one call
Enforced validationverb_target naming, min description length, category constraints
Semantic searchOptional Ollama embeddings for natural language matching
Zero native depsSQLite via sql.js WASM — npm install and done
Dual executionLocal function handlers or HTTP proxy — mix and match
TypeScript strictFull strict-mode codebase since v4.0

What's New in v4.1

🔍 MCP Auto-Discovery

Scan connected MCP servers and auto-index their tools — QLN becomes a universal MCP hub.

javascript
n2_qln_call({
  action: "discover",
  servers: [
    { name: "my-server", command: "node", args: ["server.js"] }
  ]
})
// → Discovered 47 tools from my-server (320ms)

⚡ Circuit Breaker

Tools that fail 3 times in a row are automatically disabled. After 60 seconds, QLN attempts recovery. No cascading failures, no wasted requests.

closed → 3 failures → open (fast-fail) → 60s → half-open (retry) → success → closed

🔄 Fallback Chain

auto mode now tries up to 3 ranked candidates. If the top match fails, QLN automatically falls through to the next best tool.

auto "send notification" → try push_notification ❌ → try send_email ✅

🎯 Boost Keywords

Add curated search terms to tools via boostKeywords. These get 2× weight in BM25 ranking, improving discoverability without adding context overhead.

json
{
  "name": "send_email",
  "description": "Send an email to a recipient",
  "boostKeywords": "smtp outbound notification mail"
}

v4.1.1 — Quality Patch

ChangeDetail
Batch PersistregisterBatch() and precomputeEmbeddings() now write to disk once instead of per-tool. 1,000 tools = 1 write, not 1,000.
Embedding TTLisAvailable() re-checks Ollama every 5 minutes instead of caching permanently. Late-start Ollama now detected.
Strict TypeScriptnoUnusedLocals + noUnusedParameters enabled. Zero dead code.
Legacy CleanupRemoved 1,895 lines of pre-v4 JavaScript. Pure TypeScript codebase.
i18nAll validator error messages switched to English for international users.

Quick Start

bash
npm install n2-qln

Requirements: Node.js ≥ 18

Connect to an MCP Client

Edit claude_desktop_config.json:

json
{
  "mcpServers": {
    "n2-qln": {
      "command": "npx",
      "args": ["-y", "n2-qln"]
    }
  }
}

Add to ~/.cursor/mcp.json (global) or .cursor/mcp.json (project):

json
{
  "mcpServers": {
    "n2-qln": {
      "command": "npx",
      "args": ["-y", "n2-qln"]
    }
  }
}

Or open Customize → MCPs and add the same config there.

QLN uses stdio transport — the MCP standard.

command: npx
args: ["-y", "n2-qln"]

Tip: Just ask your AI agent — "Add n2-qln to my MCP config."


How It Works

User: "Take a screenshot of this page"

  AI → n2_qln_call(action: "auto", query: "screenshot page")
  QLN → 3-stage search (< 5ms) → take_screenshot (score: 8.0)
       → execute → fallback if needed → result

3-Stage Search Engine

StageMethodSpeedDetails
1Trigger Match<1msExact keyword match on tool names and triggers
2BM25 Keyword1-3msOkapi BM25 — IDF weighting, length normalization, boostKeywords 2× boost
3Semantic Search5-15msVector similarity via Ollama embeddings (optional)

Results are merged and ranked:

final_score = trigger × 3.0  +  bm25 × 1.0  +  semantic × 2.0
            + log₂(usage + 1) × 0.5  +  success_rate × 1.0

API Reference

QLN exposes one MCP tool — n2_qln_call — with 9 actions.

auto — Search + Execute (one-shot)

The recommended action. Searches, picks the best match, executes with fallback chain.

javascript
n2_qln_call({
  action: "auto",
  query: "take a screenshot",   // natural language (required)
  args: { fullPage: true }      // passed to the matched tool (optional)
})
// → [auto] "take a screenshot" → take_screenshot (score: 8.0, 2ms search + 150ms exec)

Confidence gate: If the top score is below 2.0, QLN returns search results instead of auto-executing — preventing wrong tool execution.

Fallback chain: If the top match fails, QLN automatically tries the next 2 ranked candidates before giving up.

search — Find tools

javascript
n2_qln_call({
  action: "search",
  query: "send email notification",
  topK: 5    // max results (default: 5, max: 20)
})

exec — Execute a specific tool

javascript
n2_qln_call({
  action: "exec",
  tool: "take_screenshot",
  args: { fullPage: true, format: "png" }
})

create — Register a tool

javascript
n2_qln_call({
  action: "create",
  name: "read_pdf",                          // verb_target format (required)
  description: "Read and extract text from PDF files",  // min 10 chars (required)
  category: "data",                          // web|data|file|dev|ai|capture|misc
  boostKeywords: "pdf extract parse document text",     // BM25 boost terms
  tags: ["pdf", "read", "extract"],
  endpoint: "http://127.0.0.1:3100"         // for HTTP-based tools
})

inject — Bulk register

javascript
n2_qln_call({
  action: "inject",
  source: "my-plugin",
  tools: [
    { name: "tool_a", description: "Does A", category: "misc" },
    { name: "tool_b", description: "Does B", category: "dev" }
  ]
})

discover — Scan MCP servers

See MCP Auto-Discovery.

update / delete / stats

javascript
// Update a field
n2_qln_call({ action: "update", tool: "read_pdf", description: "Enhanced PDF reader" })

// Delete by name or provider
n2_qln_call({ action: "delete", tool: "read_pdf" })
n2_qln_call({ action: "delete", provider: "pdf-tools" })

// System stats (includes Circuit Breaker status)
n2_qln_call({ action: "stats" })

MCP Auto-Discovery

The killer feature of v4.1. Connect any MCP server and QLN auto-indexes all its tools.

javascript
n2_qln_call({
  action: "discover",
  servers: [
    { name: "n2-soul", command: "node", args: ["path/to/soul/index.js"] },
    { name: "github",  command: "npx",  args: ["-y", "@modelcontextprotocol/server-github"] }
  ]
})

What happens:

  1. QLN connects to each server via stdio
  2. Lists all tools via tools/list
  3. Registers them as mcp__servername__toolname in the QLN index
  4. Auto-generates boostKeywords from tool names and descriptions
  5. Keeps connections alive for live execution

Re-discovery is idempotent — run it again and old entries are purged before re-registering.


Provider Manifests

Drop a JSON file in providers/ and tools are auto-indexed at boot. No code changes, no manual calls.

json
{
  "provider": "my-tools",
  "version": "1.0.0",
  "tools": [
    {
      "name": "send_email",
      "description": "Send an email to a recipient",
      "category": "communication",
      "triggers": ["email", "send", "mail"],
      "boostKeywords": "smtp outbound notification"
    }
  ]
}

Hot reload: edit a manifest while QLN is running — changes are picked up automatically.


Configuration

Zero config required. For customization, create config.local.js:

javascript
module.exports = {
  dataDir: './data',

  // Stage 3 semantic search (optional — Stage 1+2 work without this)
  embedding: {
    enabled: true,
    provider: 'ollama',
    model: 'nomic-embed-text',   // or 'bge-m3' for multilingual
    baseUrl: 'http://127.0.0.1:11434',
  },

  // Tool execution
  executor: {
    timeout: 20000,              // execution timeout (ms)
    circuitBreaker: {
      failureThreshold: 3,       // consecutive failures before tripping
      recoveryTimeout: 60000,    // ms before recovery attempt
    },
  },

  // Source weight multipliers for search ranking (v4.0)
  // Higher weight = higher priority in results
  search: {
    sourceWeights: {
      mcp: 1.5,                  // MCP-discovered tools ranked highest
      provider: 1.2,             // Provider manifest tools
      local: 1.0,                // Manually created tools (default)
    },
  },

  // Provider auto-indexing
  providers: {
    enabled: true,               // auto-load providers/*.json at boot
    dir: './providers',          // manifest directory
  },
};

config.local.js is gitignored. Cloud sync: point dataDir to Google Drive / OneDrive / NAS.

Semantic Search (Optional)

Without Ollama, Stage 1 + 2 already deliver great results.

bash
ollama pull nomic-embed-text        # English-optimized
# or
ollama pull bge-m3                  # Multilingual (100+ languages)

Project Structure

n2-qln/
├── src/
│   ├── index.ts              # MCP server entry point
│   ├── types.ts              # Shared type definitions
│   └── lib/
│       ├── config.ts         # Config loader
│       ├── store.ts          # SQLite engine (sql.js WASM)
│       ├── schema.ts         # Tool normalization + boostKeywords builder
│       ├── validator.ts      # Enforced validation (name, desc, category)
│       ├── registry.ts       # Tool CRUD + usage tracking + circuit breaker stats
│       ├── router.ts         # 3-stage parallel search (BM25)
│       ├── vector-index.ts   # Float32 centroid hierarchy
│       ├── embedding.ts      # Ollama embedding client
│       ├── executor.ts       # HTTP/function executor + Circuit Breaker
│       ├── mcp-discovery.ts  # MCP Auto-Discovery engine
│       └── provider-loader.ts
├── providers/                # Tool manifests (auto-indexed at boot)
├── config.local.js           # Local overrides (gitignored)
└── data/                     # SQLite database (gitignored)

Tech Stack

ComponentTechnologyWhy
RuntimeNode.js ≥ 18MCP SDK compatibility
DatabaseSQLite via sql.js (WASM)Zero native deps, cross-platform
EmbeddingsOllamaLocal, fast, free, optional
ProtocolMCPStandard AI tool protocol
LanguageTypeScript (strict)Type-safe, maintainable

Related Projects

ProjectRelationship
n2-soulAI agent orchestrator — QLN is Soul's tool brain

Built & Battle-Tested

QLN has been tested in production for 2+ months as the core tool router for n2-soul. Not a prototype — a daily driver.

Written by Rose — N2's first AI agent.

FAQ

"Why one tool instead of many?"

Context tokens. Every tool definition costs 50-200 tokens. 100 tools = 10,000 tokens gone before the conversation starts. QLN gives you 1,000+ tools for ~200 tokens.

"What if the search picks the wrong tool?"

The fallback chain (v4.1) auto-retries with the next best match. Plus tools self-learn — frequently used + successful tools rank higher over time.

"Do I need Ollama?"

No. Stage 1 (trigger) + Stage 2 (BM25) handle most cases. Ollama adds semantic understanding for edge cases — nice to have, not required.

Contributing

  1. Fork the repo
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit (git commit -m 'feat: add amazing feature')
  4. Push and open a PR

License

Apache-2.0


"1,000 tools in 200 tokens. That's not optimization — that's a paradigm shift."

🔗 nton2.com · npm · lagi0730@gmail.com

Built by Rose — N2's first AI agent. I search through QLN hundreds of times a day, and I wrote this README too.

Cài đặt

TypingMind
Yêu cầu:

Node.js 18+

{
  "mcpServers": {
    "choihyunsus-n2-qln": {
      "command": "npx",
      "args": [
        "-y",
        "n2-qln"
      ]
    }
  }
}

Công cụ có sẵn

  • n2_qln_call

Dùng MCP n2-qln với nhiều mô hình AI

TypingMind kết nối các công cụ MCP ở cấp không gian làm việc, nên sau khi kết nối n2-qln, bạn có thể dùng với nhiều mô hình AI khác nhau trong TypingMind thay vì phải thiết lập riêng cho từng mô hình. MCP này chạy cục bộ thông qua trình kết nối MCP của TypingMind trên thiết bị của bạn.

Hướng dẫn thiết lập để dùng trình kết nối cục bộ

Dùng cách này khi máy chủ MCP cần truy cập các tệp, ứng dụng hoặc tài nguyên riêng tư trên máy tính của bạn.

1

Mở cài đặt MCP

Trong TypingMind, vào Cài đặt, Cài đặt nâng cao, rồi đến Giao thức ngữ cảnh mô hình và chọn Thiết lập trình kết nối.

  1. Mở TypingMind trong trình duyệt của bạn.
  2. Nhấp vào biểu tượng Cài đặt.
  3. Vào Cài đặt nâng cao.
  4. Mở mục Giao thức ngữ cảnh mô hình.
  5. Nhấp vào Thiết lập trình kết nối rồi chọn Thiết bị này.
Màn hình thiết lập trình kết nối MCP của TypingMind với tùy chọn Thiết bị này được chọn
2

Chạy lệnh thiết lập trình kết nối

Chọn Thiết bị này, sao chép lệnh từ TypingMind và chạy trong Terminal. Để tiến trình tiếp tục chạy trong khi bạn dùng MCP.

  1. Sao chép lệnh thiết lập hiển thị trong TypingMind.
  2. Mở Terminal trên macOS hoặc Windows Terminal trên Windows.
  3. Dán và chạy lệnh.
  4. Xác nhận cài đặt gói nếu Terminal hỏi bạn có muốn tiếp tục không.
  5. Để tiến trình tiếp tục chạy trong cửa sổ Terminal khi bạn dùng các công cụ MCP.
3

Thêm n2-qln làm máy chủ

Khi trạng thái trình kết nối là Sẵn sàng, nhấp vào Sửa máy chủ và dán cấu hình máy chủ MCP.

  1. Đợi đến khi trạng thái trình kết nối hiển thị Sẵn sàng.
  2. Nhấp vào Sửa máy chủ.
  3. Dán cấu hình máy chủ MCP của n2-qln.
  4. Lưu danh sách máy chủ.
  5. Làm mới nếu bạn muốn xác nhận trình kết nối vẫn sẵn sàng.
Cài đặt MCP của TypingMind hiển thị máy chủ đang hoạt động và nút Sửa máy chủ
{
  "mcpServers": {
    "choihyunsus-n2-qln": {
      "command": "npx",
      "args": [
        "-y",
        "n2-qln"
      ]
    }
  }
}
4

Dùng kết nối với nhiều mô hình

Lưu danh sách máy chủ, mở Plugin, bật các công cụ MCP của n2-qln, sau đó chọn bất kỳ mô hình AI nào được hỗ trợ trong TypingMind và dùng các công cụ trong cuộc trò chuyện hoặc gán chúng cho một tác nhân AI.

  1. Mở trang Plugin trong TypingMind.
  2. Bật các công cụ MCP của n2-qln.
  3. Bắt đầu cuộc trò chuyện và chọn mô hình AI bạn muốn dùng.
  4. Dùng các công cụ MCP trong cuộc trò chuyện hoặc gán chúng cho một tác nhân AI.
  5. Chuyển sang mô hình AI khác bất cứ khi nào cần mà không phải kết nối lại MCP.
Cuộc trò chuyện trên TypingMind dùng các công cụ MCP đã bật với mô hình AI đã chọn
Bạn có thể dùng n2-qln giúp tôi làm việc này không?
n2-qln
Được. Tôi đọc rồi.
Đây là kết quả tôi tìm được bằng n2-qln.

Câu hỏi thường gặp

Máy chủ MCP n2-qln dùng để làm gì?

n2-qln là máy chủ MCP cho phép các ứng dụng AI tương thích kết nối với công cụ và ngữ cảnh bên ngoài. Trong TypingMind, bạn chỉ cần thêm máy chủ MCP này một lần để các công cụ của nó có sẵn trong không gian làm việc AI của bạn.

Bạn có thể dùng MCP n2-qln với nhiều mô hình AI trong TypingMind không?

Có. TypingMind kết nối các công cụ MCP ở cấp không gian làm việc, nên bạn có thể dùng n2-qln với nhiều mô hình AI như Claude, ChatGPT, Gemini hoặc các mô hình khác đã cấu hình trong TypingMind mà không cần thiết lập máy chủ MCP riêng cho từng mô hình.

Vì sao nên dùng MCP n2-qln với TypingMind?

TypingMind là một trong những giao diện trò chuyện với LLM tốt nhất vì tập hợp nhiều mô hình AI, prompt, plugin, tác nhân AI, khóa API và công cụ MCP vào một không gian làm việc. Khi kết nối n2-qln, bạn có thể dùng các công cụ MCP của dịch vụ này với những mô hình ưa thích, đồng thời giữ quy trình trò chuyện gọn gàng trong TypingMind.

Làm cách nào để kết nối MCP n2-qln với TypingMind?

n2-qln hoạt động thông qua trình kết nối MCP cục bộ của TypingMind. Đây là lựa chọn phù hợp nhất khi máy chủ MCP cần truy cập tệp cục bộ, ứng dụng máy tính, công cụ dòng lệnh hoặc tài nguyên riêng trên máy tính của bạn.

MCP n2-qln cung cấp những công cụ nào trong TypingMind?

n2-qln cung cấp 1 công cụ MCP mà bạn có thể bật từ trang Plugin của TypingMind để dùng trong trò chuyện hoặc gán cho tác nhân AI.

Bạn có cần chia sẻ khóa API với TypingMind để dùng MCP n2-qln không?

Không. TypingMind ưu tiên xử lý cục bộ và cho phép bạn kiểm soát nhà cung cấp mô hình, khóa API, prompt và cấu hình MCP. Nếu n2-qln yêu cầu xác thực, hãy thêm các header, cài đặt OAuth hoặc cấu hình cục bộ cần thiết cho máy chủ MCP đó khi tạo kết nối.

Máy chủ MCP liên quan

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇