TypeScript Python

Mesh Auth SDK

Add identity and org context to any internal tool. Three lines of code, zero auth knowledge required.

Last Updated: 2026-04-07 17:21 PDT

Install

Internal SDK artifacts are hosted directly on mesh.langgenius.ai. TypeScript uses versioned npm tarballs; Python uses a versioned wheel.

Install from direct wheel URL

$ pip install https://mesh.langgenius.ai/downloads/langgenius_mesh_auth-0.2.0-py3-none-any.whl

Install from direct tarball URLs

Install both the shared contracts package and the SDK tarball in one command.

$ npm install \
  https://mesh.langgenius.ai/downloads/langgenius-mesh-contracts-0.2.0.tgz \
  https://mesh.langgenius.ai/downloads/langgenius-mesh-auth-0.2.0.tgz

Client Mode

For CLI tools and local scripts. Users log in once with mesh login, the SDK reads their credentials automatically.

import { MeshAuth } from '@langgenius/mesh-auth'

const auth = new MeshAuth()
const me = await auth.whoami()       // "Who am I?"

console.log(me.email)             // luyu@langgenius.ai
console.log(me.displayName)       // Luyu Zhang
console.log(me.primaryDepartment) // CEO Office
console.log(me.isAdmin())         // true
from mesh_auth import MeshAuth

auth = MeshAuth()
me = auth.whoami()               # "Who am I?"

print(me.email)                  # luyu@langgenius.ai
print(me.display_name)           # Luyu Zhang
print(me.primary_department)     # CEO Office
print(me.is_admin())             # True

For CI/CD or bots without a login session, use an Access Key:

const auth = MeshAuth.fromAccessKey(process.env.MESH_ACCESS_KEY)
auth = MeshAuth.from_access_key(os.environ["MESH_ACCESS_KEY"])

Server Mode

For web apps and backend services. Verify incoming requests: "Who is this person, and can they do this?"

import { MeshAuth, NotAuthenticatedError } from '@langgenius/mesh-auth'

// Initialize with your system Access Key
const mesh = MeshAuth.fromAccessKey(process.env.MESH_ACCESS_KEY)

// Verify the request sender's identity
const user = await mesh.verifyToken(req.headers.authorization)

user.email                           // minco@langgenius.ai
user.isInDepartment('Engineering')  // true
user.primaryDepartment               // Backend

// Then query more data with your own key
const mgr = await mesh.getManager(user.email)
const team = await mesh.getDepartmentMembers('Backend')
import os
from mesh_auth import MeshAuth, NotAuthenticatedError

# Initialize with your system Access Key
mesh = MeshAuth.from_access_key(os.environ["MESH_ACCESS_KEY"])

# Verify the request sender's identity
user = mesh.verify_token(request.headers.get("Authorization"))

user.email                              # minco@langgenius.ai
user.is_in_department("Engineering")    # True
user.primary_department                 # Backend

# Then query more data with your own key
mgr = mesh.get_manager(user.email)
team = mesh.get_department_members("Backend")

Express / Hono middleware

const mesh = MeshAuth.fromAccessKey(process.env.MESH_ACCESS_KEY)

async function requireEmployee(req, res, next) {
  try {
    req.meshUser = await mesh.verifyToken(req.headers.authorization)
    next()
  } catch (e) {
    if (e instanceof NotAuthenticatedError)
      return res.status(401).json({ error: 'Unauthorized' })
    return res.status(500).json({ error: 'Auth service unavailable' })
  }
}

app.post('/deploy', requireEmployee, (req, res) => {
  if (!req.meshUser.isInDepartment('Engineering'))
    return res.status(403).json({ error: 'Only Engineering can deploy' })
  // ... deploy logic
})

FastAPI dependency injection

from fastapi import Depends, Header, HTTPException
from mesh_auth import MeshAuth, NotAuthenticatedError

mesh = MeshAuth.from_access_key(os.environ["MESH_ACCESS_KEY"])

def require_employee(authorization: str = Header()):
    try:
        return mesh.verify_token(authorization)
    except NotAuthenticatedError:
        raise HTTPException(401, "Unauthorized")

@app.post("/deploy")
def deploy(user=Depends(require_employee)):
    if not user.is_in_department("Engineering"):
        raise HTTPException(403, "Only Engineering can deploy")
    # ... deploy logic
verifyToken() uses the client's token to call /auth/me. Subsequent queries (getManager, etc.) use your server's own Access Key. For high-traffic endpoints, cache the result (recommended TTL ≤ 5 min).

Identity & Permissions

Check authentication

// Returns true if credentials exist and are valid
const ok = await auth.isAuthenticated()

// Or require it — prints error and exits if not logged in
await auth.requireAuth()
# Returns True if credentials exist and are valid
ok = auth.is_authenticated()

# Or require it — prints error and exits if not logged in
auth.require_auth()

Role checks

const me = await auth.whoami()

me.isAdmin()     // role === 'admin'
me.isEditor()    // role === 'admin' || 'editor'
me.isViewer()    // true (everyone is at least viewer)
me = auth.whoami()

me.is_admin()      # role == "admin"
me.is_editor()     # role in ("admin", "editor")
me.is_viewer()     # True (everyone is at least viewer)

Department checks

me.isInDepartment('Engineering')  // matches name or localName
me.isInDepartment('工程')          // localName works too
me.primaryDepartment              // "CEO Office"
me.is_in_department("Engineering")  # matches name or local_name
me.is_in_department("工程")          # local_name works too
me.primary_department              # "CEO Office"
The SDK provides identity and org context. Business authorization ("can this person deploy?") is your tool's responsibility.

Queries

Employees

// By email or employee number
const emp = await auth.getEmployee('minco@langgenius.ai')
const emp = await auth.getEmployee('LG-0003')

// Manager and reports
const mgr = await auth.getManager('minco@langgenius.ai')
const reports = await auth.getReports('alice@langgenius.ai')

// Departments of an employee
const depts = await auth.getDepartments('minco@langgenius.ai')
# By email or employee number
emp = auth.get_employee("minco@langgenius.ai")
emp = auth.get_employee("LG-0003")

# Manager and reports
mgr = auth.get_manager("minco@langgenius.ai")
reports = auth.get_reports("alice@langgenius.ai")

# Departments of an employee
depts = auth.get_departments("minco@langgenius.ai")

Organization

// Department members (supports localName)
const team = await auth.getDepartmentMembers('Backend')
const team = await auth.getDepartmentMembers('后端')

// Recursive (include sub-departments)
const all = await auth.getDepartmentMembers('Engineering', { recursive: true })

// Org chart
const tree = await auth.getOrgChart()
const sub = await auth.getOrgChart({ rootId: 'Backend' })
# Department members (supports local_name)
team = auth.get_department_members("Backend")
team = auth.get_department_members("后端")

# Recursive (include sub-departments)
all = auth.get_department_members("Engineering", recursive=True)

# Org chart
tree = auth.get_org_chart()
sub = auth.get_org_chart(root_id="Backend")

Error Handling

import {
  MeshAuth,
  NotAuthenticatedError,
  MeshApiError,
  EmployeeNotFoundError,
  NetworkError,
} from '@langgenius/mesh-auth'

try {
  const me = await auth.whoami()
} catch (e) {
  if (e instanceof NotAuthenticatedError) {
    console.error('Run `mesh login` first.')
  }
}
from mesh_auth import (
    MeshAuth,
    NotAuthenticatedError,
    MeshApiError,
    EmployeeNotFoundError,
    NetworkError,
)

try:
    me = auth.whoami()
except NotAuthenticatedError:
    print('Run `mesh login` first.')
ErrorWhenWhat to do
NotAuthenticatedErrorNo credentials or refresh failedPrompt user to mesh login
EmployeeNotFoundErrorEmail or employee number not in systemCheck the identifier
MeshApiErrorMesh API returned 4xx/5xxShow e.code + e.message
NetworkErrorCannot reach Mesh APICheck network / VPN

Configuration

Options

const auth = new MeshAuth({
  apiUrl: 'http://localhost:3456',             // default: https://mesh.langgenius.ai
  credentialsPath: '/custom/creds.json',       // default: ~/.mesh/credentials.json
  timeout: 5000,                               // default: 10000ms
  retries: 2,                                  // default: 1
  debug: true,                                 // default: false
})
auth = MeshAuth(
    api_url="http://localhost:3456",          # default: https://mesh.langgenius.ai
    credentials_path="/custom/creds.json",   # default: ~/.mesh/credentials.json
    timeout=5,                                # default: 10 (seconds)
    retries=2,                                # default: 1
    debug=True,                               # default: False
)

Environment variables

VariableEffect
MESH_API_URLOverride API base URL
MESH_ACCESS_KEYUse Access Key auth (skips credentials file)
MESH_AUTH_DEBUGSet to 1 to enable debug logging

Security

MeasureDetail
Credential file permissions~/.mesh/credentials.json must be 0600. SDK warns if not.
HTTPS enforcedRefuses non-HTTPS connections except localhost / 127.0.0.1
Debug log maskingTokens are masked (mesh_sk_abc1****) in all log output
Refresh token rotationEach refresh issues a new token; old one is immediately invalidated
Client mode is not a security boundary. The SDK runs on the user's machine — isAdmin() can be tampered with. Client-side role checks are UX hints (show/hide UI, early error messages), not access control. Real security is enforced server-side: Mesh API validates every token independently, and verifyToken() runs on your server where users can't touch it.

Type Exports

import type {
  MeshUser,           // whoami() return type
  MeshEmployee,       // getEmployee() return type
  MeshDepartment,     // getDepartments() return type
  MeshOrgChartNode,   // getOrgChart() return type
} from '@langgenius/mesh-auth'
# All types are dataclasses with full type hints
from mesh_auth import (
    MeshUser,              # whoami() return type
    DepartmentMembership,  # get_departments() item type
    BasicEmployee,         # get_manager() / get_reports() type
)
# get_employee() returns a plain dict (full API response)